TypeScript: Remove a Property from an Object

Introduction

Just like in any language that has them, objects are an important part of JS/TS, allowing us to store collections of values with different types. While working with objects, we often need to change their properties - in this case, removing them.

This Byte will show you the various ways of removign a property from an object in TypeScript, starting with the removal of a property.

Removing a Property in TypeScript

Removing a property from an object in TypeScript is fairly straightforward. We use the delete keyword followed by the object and the property name. Let's take a look at an example:

let user = {
    name: 'John Doe',
    age: 25,
    occupation: 'Software Developer'
};

delete user.occupation;

console.log(user);

The output will be:

{
    name: 'John Doe',
    age: 25
}

As you can see, the occupation property has been successfully removed! That was easy :)

Removing Non-Optional Properties

Note: In case you're not familiar, in TypeScript, a non-optional property is a property that must exist in an object. It is defined without a question mark (?) after the property name.

When working with TypeScript objects, you might encounter a situation where you need to remove a non-optional property. However, TypeScript will throw an error if you try to delete a non-optional property directly.

type User = {
    name: string;
    age: number;
    occupation: string;
};

let user: User = {
    name: 'John Doe',
    age: 25,
    occupation: 'Software Developer'
};

delete user.occupation; // Error: The operand of a 'delete' operator must be optional.

To handle this case, you can use a type assertion to tell TypeScript that the object will still conform to its type after the property is deleted.

delete (user as {occupation?: string}).occupation;

Now, TypeScript will not throw an error, and the occupation property will be removed as expected.

The trick here is this part: (user as {occupation?: string}). This is a type assertion that tells the compiler to treat user as an object with an optional occupation property of type string. It doesn't change the runtime behavior but provides a hint to the compiler about the expected shape of the object.

Using Types Instead of Interfaces

In TypeScript, both type and interface can be used to define the shape of an object. However, when it comes to manipulating object properties, type has some advantages.

One advantage is the ability to create a new type by omitting certain properties from an existing type using the Omit utility type. This is not possible with interfaces.

type User = {
    name: string;
    age: number;
    occupation: string;
};

type UserWithoutOccupation = Omit<User, 'occupation'>;

let user: UserWithoutOccupation = {
    name: 'John Doe',
    age: 25
};

console.log(user);

In this example, UserWithoutOccupation is a new type that has all the properties of User except for occupation. This allows us to create an object user that does not have the occupation property, and TypeScript will not complain about it!

Destructuring for Property Removal

Destructuring in TypeScript is a nice feature that allows us to unpack values from arrays, or properties from objects, into their distinct variables. This can be very useful when we want to remove a property from an object, among other object manipulations.

Let's take a look at an example:

let obj = { a: 1, b: 2, c: 3 };
let { a, ...newObj } = obj;
console.log(newObj); // Output: { b: 2, c: 3 }

In the code above, we're creating a new object called newObj that contains all the properties of obj except for a. This is achieved by destructuring obj and excluding a from the newly formed object.

Excluding Dynamic Keys

There might be situations where you need to exclude dynamic keys from an object. TypeScript doesn't directly support this, but we can use a workaround with the help of a helper function. Here's how you can do it:

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

function excludeKey<T extends object, U extends keyof any>(obj: T, key: U) {
    const { [key]: _, ...newObj } = obj;
    return newObj;
}

let obj = { a: 1, b: 2, c: 3 };
let newObj = excludeKey(obj, 'b');
console.log(newObj); // Output: { a: 1, c: 3 }

In the code above, the excludeKey function takes an object and a key, and returns a new object excluding the specified key. This is a handy way to exclude dynamic keys from an object.

Using Partial Type for Property Removal

TypeScript provides a utility type Partial<T>, which makes all properties in T optional. This can be useful for property removal in some cases. Here's an example:

type MyObject = {
  a: number;
  b: number;
  c: number;
};

function removeProperty<T, K extends keyof T>(obj: T, key: K): Partial<T> {
  const { [key]: _, ...newObj } = obj;
  return newObj;
}

let obj: MyObject = { a: 1, b: 2, c: 3 };
let newObj = removeProperty(obj, 'a');
console.log(newObj); // Output: { b: 2, c: 3 }

In this code, removeProperty function uses Partial<T> to indicate that the returned object may not contain all properties of T.

Using Omit and Pick for Property Removal

The Omit<T, K> utility type in TypeScript constructs a type by picking all properties from T and then removing K. On the other hand, Pick<T, K> does the exact opposite, it creates a new type by picking K properties from T.

Let's see how we can use these utility types for property removal:

type MyObject = {
  a: number;
  b: number;
  c: number;
};

type NewObject = Omit<MyObject, 'a'>;
let obj: NewObject = { b: 2, c: 3 };
console.log(obj); // Output: { b: 2, c: 3 }

type PickObject = Pick<MyObject, 'b' | 'c'>;
let pickObj: PickObject = { b: 2, c: 3 };
console.log(pickObj); // Output: { b: 2, c: 3 }

In the above code, NewObject type is created by omitting a from MyObject, and PickObject is created by picking b and c from MyObject. These utility types provide a nice way to manipulate object properties in TypeScript.

Lodash for Property Removal in TypeScript

Of course, the popular JavaScript utility library, Lodash, provides helpful methods for manipulating arrays, objects, and other data types. One of these methods is the omit method, which we can use to remove properties from an object in TypeScript.

First, you need to install Lodash in your project. You can do this by running the following command in your terminal:

$ npm install lodash

Once installed, you can import the omit method from Lodash:

import { omit } from 'lodash';

Here is an example where we have a user object, and we want to remove the password property from it:

import { omit } from 'lodash';

let user = {
    name: 'John Doe',
    email: '[email protected]',
    password: 'password123'
};

let userWithoutPassword = omit(user, 'password');

console.log(userWithoutPassword);

The output of the code will be:

{ name: 'John Doe', email: '[email protected]' }

Note: The omit method does not modify the original object. Instead, it returns a new object with the specified properties removed.

As you can see, the password property has been removed from the user object.

While there are quite a few ways to remove properties from objects, the nice thing about using Lodash is that it's already being used in many projects and it's a much cleaner way to get the job done than some of those shown earlier in this Byte.

Conclusion

In this Byte we showed different methods of removing properties, like using TypeScript's built-in features like the Partial type, Omit and Pick utilities, and destructuring. We also saw how to handle non-optional properties and dynamic keys, and the differences between types and interfaces. Lastly, we explained how to use the Lodash library for removing properties.

Last Updated: August 16th, 2023
Was this helpful?
Project

React State Management with Redux and Redux-Toolkit

# javascript# React

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup
Uchechukwu Azubuko
Details

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms