How to useObject destructuring and rest syntax in Typescript

In this approach, we leverage object destructuring along with the rest syntax to create a new object that excludes the specified key. We use object destructuring to extract all properties of the original object except the one we want to remove, and then use the rest syntax to collect these properties into a new object.

Example: In this example, we’ll use object destructuring and rest syntax to remove the key “year” from the original object.

JavaScript
interface MyObject {
    [key: string]: any;
}

const originalObject: MyObject = { name: 'GFG', year: 2024, city: 'Noida' };
console.log("Original Object:");
console.log(originalObject);

const keyToRemove: string = 'year';

// Using object destructuring and rest syntax to remove the specified key
const { [keyToRemove]: removedKey, ...newObject } = originalObject;

console.log("After key removal:");
console.log(newObject);

Output

Original Object:
{ name: 'GFG', year: 2024, city: 'Noida' }
After key removal:
{ name: 'GFG', city: 'Noida' }


How to Remove a Key from TypeScript Object ?

In TypeScript, objects are mutable, which means you can modify them by adding, updating, or removing properties. Removing a key from an object involves either creating a new object without the specified key or using certain built-in methods to achieve the desired result.

Below are the approaches used to remove a key from TypeScript object:

Table of Content

  • Approach 1: Using spread operator
  • Approach 2: Using delete keyword
  • Approach 3: Using Object.assign()
  • Approach 4: Using Object destructuring and rest syntax

Similar Reads

Approach 1: Using spread operator

This approach involves creating a new object that excludes the key you want to remove. The spread operator (…) is used to copy the existing properties of the object into a new object, excluding the specified key....

Approach 2: Using delete keyword

To remove a key from a TypeScript object, you can use the delete operator or create a new object without the specified key....

Approach 3: Using Object.assign()

To remove a key from an object using Object.assign(), we create a new object by copying all properties from the original object except for the specified key....

Approach 4: Using Object destructuring and rest syntax

In this approach, we leverage object destructuring along with the rest syntax to create a new object that excludes the specified key. We use object destructuring to extract all properties of the original object except the one we want to remove, and then use the rest syntax to collect these properties into a new object....

Contact Us