How to Remove a Property from an Object in TypeScript?

As a developer working on a complex project for a client in New York, I recently faced the challenge of dynamically modifying objects without causing type errors. In this tutorial, I will explain how to remove a property from an object in TypeScript using different methods with examples.

Remove a Property from an Object in TypeScript

Now, let me show you different methods to remove a property from an object in TypeScript.

1. Using the delete Operator

The best way to remove a property from an object in JavaScript and TypeScript is using the delete operator. However, this method has some caveats in TypeScript.

Let me show you an example.

interface User {
  name: string;
  age: number;
  email?: string;
}

const user: User = {
  name: "John Doe",
  age: 30,
  email: "john.doe@example.com",
};

delete user.email;
console.log(user); // Output: { name: 'John Doe', age: 30 }

While the delete operator works, it does not always play well with TypeScript’s type system. If the property is not optional, TypeScript will throw an error. For example, trying to delete a non-optional property will result in a type error.

Here is the exact output in the screenshot below:

Remove a Property from an Object in TypeScript

Check out Optional Parameters in TypeScript Interfaces

2. Type-Safe Property Removal with Destructuring

A more type-safe method involves using object destructuring along with the rest syntax. This approach ensures that TypeScript’s type system is respected.

interface User {
  name: string;
  age: number;
  email: string;
}

const user: User = {
  name: "Jane Smith",
  age: 25,
  email: "jane.smith@example.com",
};

const { email, ...rest } = user;
console.log(rest); // Output: { name: 'Jane Smith', age: 25 }

In this example, we destructure the user object, extracting the email property and collecting the remaining properties into a new object rest. This method is type-safe and does not alter the original object.

Here is the exact output in the screenshot below:

How to Remove a Property from an Object in TypeScript

Read Check if an Object is Type of Interface in TypeScript

3. Create a Utility Function

You can create a utility function to streamline the process of removing properties in TypeScript from an object. This function will accept an object and a list of keys to remove, returning a new object without those keys.

type AnyObject = { [key: string]: any };

function removeProperties<T extends AnyObject, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> {
  const newObj = { ...obj };
  keys.forEach(key => delete newObj[key]);
  return newObj;
}

const user = {
  name: "Michael Johnson",
  age: 40,
  email: "michael.johnson@example.com",
  address: "123 Main St, Springfield, USA",
};

const updatedUser = removeProperties(user, ["email", "address"]);
console.log(updatedUser); // Output: { name: 'Michael Johnson', age: 40 }

Read Declare and Use TypeScript Interfaces with Nested Arrays of Objects

4. Using Omit Type Utility

TypeScript provides a built-in utility type called Omit that can be used to create a new type by excluding specific properties from an existing type. This is particularly useful when you need to ensure type safety.

interface User {
  name: string;
  age: number;
  email: string;
  address: string;
}

type UserWithoutEmail = Omit<User, "email">;

const user: User = {
  name: "Emily Davis",
  age: 28,
  email: "emily.davis@example.com",
  address: "456 Oak St, Springfield, USA",
};

const removeEmail = ({ email, ...rest }: User): UserWithoutEmail => rest;

const updatedUser = removeEmail(user);
console.log(updatedUser); // Output: { name: 'Emily Davis', age: 28, address: '456 Oak St, Springfield, USA' }

In this example, the Omit type is used to create a new type UserWithoutEmail, which excludes the email property from the User interface. The removeEmail function then uses destructuring to remove the email property and return an object of type UserWithoutEmail.

Read TypeScript Interface Function Properties

Practical Example: API Responses

Consider a scenario where you receive a user object from an API, and you need to remove certain properties before storing it in your state management system. Here’s how you can handle this:

interface ApiUser {
  id: string;
  name: string;
  age: number;
  email: string;
  password: string;
}

type SafeUser = Omit<ApiUser, "password">;

const sanitizeUser = (user: ApiUser): SafeUser => {
  const { password, ...safeUser } = user;
  return safeUser;
};

const apiResponse: ApiUser = {
  id: "123",
  name: "Alice Brown",
  age: 35,
  email: "alice.brown@example.com",
  password: "secret123",
};

const sanitizedUser = sanitizeUser(apiResponse);
console.log(sanitizedUser); // Output: { id: '123', name: 'Alice Brown', age: 35, email: 'alice.brown@example.com' }

In this example, the sanitizeUser function removes the password property from the user object received from the API, ensuring that sensitive information is not stored.

Conclusion

In this tutorial, I explained how to remove properties from an object in TypeScript using different methods. The delete operator is quick and easy but may not always be type-safe. Using destructuring with the rest syntax provides a type-safe alternative. You can also create a utility function or you can also use TypeScript’s Omit type utility to remove properties from a TypeScript object.

You may also like: