How to usedelete keyword in Typescript
To remove a key from a TypeScript object, you can use the delete
operator or create a new object without the specified key.
Syntax:
delete objectName[keyToRemove];
Example: In this example, the age property is removed from the person object using the delete keyword.
interface Person {
name: string;
age: number;
city: string;
}
const person: Person =
{ name: 'Alice', age: 30, city: 'London' };
// Ensuring keyToRemove is a valid key of Person
const keyToRemove: keyof Person = 'age';
console.log("Original Object");
console.log(person);
// Deleting the specified key from the object
delete person[keyToRemove];
console.log("After key removal");
console.log(person);
Output:
Original Object
{ name: 'Alice', age: 30, city: 'London' }
After key removal
{ name: 'Alice', city: 'London' }
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
Contact Us