
In this article, we are going to explore a practical, elegant function written in TypeScript called makeKeyRemover. This function removes one or more keys from an object while maintaining type safety. Let's break it down line by line and then visualize its applications through various examples.
A Deep Dive Into makeKeyRemover#
export const makeKeyRemover = <Key extends string | number | symbol>(
keys: Key[]
) => {
return <Obj extends Record<Key, unknown>>(obj: Obj): Omit<Obj, Key> => {
const result = { ...obj };
keys.forEach((key) => {
if (key in obj) {
// Check if key is present in Obj
delete result[key]; // If yes, delete key
}
});
return result;
};
};
This first line exports a constant named makeKeyRemover, which is a generic function. The function accepts an array of keys as a parameter. These keys can be of type string, number, or symbol.
return <Obj extends Record<Key, unknown>>(obj: Obj): Omit<Obj, Key> => {
Here the function defines its return type. It takes an object and makes sure all of its keys are subtypes of Key.
const result = { ...obj };
The function uses the spread operator (...) to create a shallow copy of the original object. This ensures not mutating the original object while deleting the keys.
if (key in obj) { delete result[key]; }
This operation checks each key in the passed object. If the key matches any in the keys array passed earlier, it deletes that key-value pair from the cloned object. The function finally returns the modified object after removing specific keys.
Let's see it in action:
const keyRemover = makeKeyRemover(["name"]);
const res = keyRemover({ name: "Jane", id: 0, age: 58 });
console.log(res); // Outputs: { id: 0, age: 58 }
In the above example, we first define keyRemover to be a new function that will remove the "name" key from any given object. We then call keyRemover with an object as an argument. As expected, it removes the "name" key and returns the rest of the object.
Practical Applications#
Consider we are dealing with user data in an application. Sometimes, we may need to limit access to some sensitive data (like passwords) while returning the user information.
const user = {
id: 1234,
name: "John Doe",
email: "john.doe@example.com",
password: "sensitive_password",
}
const userDataRemover = makeKeyRemover(['password']);
const sanitizedUser = userDataRemover(user);
console.log(sanitizedUser);
// Outputs: { id: 1234, name: "John Doe", email: "john.doe@example.com"}
As seen here, makeKeyRemover helps us sanitize our user data without mutating the original user object and also maintaining type correctness.
Wrapping Up#
The makeKeyRemover function is a powerful utility in TypeScript for removing specified keys from objects. It ensures type safety while performing this operation and preserves immutability by not modifying the original object. Hence, through this guide, developers can gain a useful tool for handling data within applications effectively. Understanding such functions aids developers in harnessing TypeScript's full power, resulting in more effective, reliable code.
Source: typescript-101 / Advanced / day8