• _hello
  • _about-me
  • _projects
  • _blog
  • _support
_contact-me
find me in:
@faeztgh
cd ../blog~/blog/key-removal-in-typescript
  • TypeScript
  • Utility Types
  • Type Safety
  • Generics

An In-Depth Guide to Key Removal in TypeScript

Learn how to build a type-safe makeKeyRemover utility in TypeScript that removes object keys without mutation, using generics and the Omit utility type.

FFaez Tgh·Dec 26, 20232 min read·344 words
// share: post linkedin
TypeScript key removal — building a type-safe makeKeyRemover utility

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#

ts
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.

ts
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.

ts
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.

ts
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:

ts
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.

ts
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

#on this page

  • A Deep Dive Into makeKeyRemover
  • Practical Applications
  • Wrapping Up
Decoding URL Parameters with TypeScript: An In-Depth Guide olderUnderstanding Namespaces in TypeScript: A Deep Divenewer

# related-posts

3 more
  • 01
    Deep Dive into Const Assertions and Utility TypesJan 16, 2024·2 min
  • 02
    Dynamic Controlled ValuesJan 30, 2024·2 min
  • 03
    Manipulating TypeScript Object Types with Omit and Pick Utility TypesNov 21, 2023·2 min