How to Remove a Property from an Object in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 24, 2022

banner

Photo from Unsplash

Remove a Property from an Object in TypeScript #

To remove a property from an object in TypeScript, mark the property as optional on the type and use the delete operator. You can only remove properties that have been marked optional from an object.

index.ts
interface Employee { id: number; name?: string; // 👈️ marked optional salary: number; } const obj: Employee = { id: 1, name: 'Bob', salary: 100, }; delete obj['name'];

We marked the name property in the Employee type to be optional, so we are able to use the delete operator to remove the property from the object.

If you try to remove a property that has not been marked as optional from the object, you'd get an error.

index.ts
interface Employee { id: number; name?: string; salary: number; } const obj: Employee = { id: 1, name: 'Bob', salary: 100, }; // ⛔️ Error: The operand of a 'delete' // operator must be optional.ts(2790) delete obj['id'];

TypeScript is telling us that if we delete the id property from the object, the object will no longer be of type Employee, because the id property is required on the Employee type.

You can use the same approach when using a type instead of an interface.

index.ts
type Employee = { id: number; name?: string; salary: number; }; const obj: Employee = { id: 1, name: 'Bob', salary: 100, }; delete obj['name'];

If you don't have access to the interface, you can use the Partial utility type to construct a new type with all properties set to optional.

index.ts
interface Employee { id: number; name: string; // 👈️ not marked optional salary: number; }; const obj: Partial<Employee> = { id: 1, name: 'Bob', salary: 100, }; delete obj['name'];
The name property is required in the Person type, so we had to use the Partial utility type to construct a new type with the properties set to optional before using the delete operator.

If you want to make only some of the properties on the interface optional, you can use the Omit and Pick utility types.

Here is an example where we mark the id and name properties as optional, but leave the salary property required.

index.ts
interface Employee { id: number; name: string; salary: number; } const obj: Partial<Pick<Employee, 'id' | 'name'>> & Omit<Employee, 'id' | 'name'> = { id: 1, name: 'Bob', salary: 100, }; delete obj['name'];

We used the Pick utility type to pick out the id and name properties from the Employee interface and make them optional.

Then we used the Omit utility type to exclude the id and name properties from the Employee interface.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.