How to remove fields from a TypeScript interface

Let’s say you have an User interface but you want to remove some fields from the interface object. Is it possible to remove a field from an interface object?

The answer is yes! You can use Omit or Pick in TypeScript to remove fields from an TypeScript interface.


interface User {
    id: string;
    first_name: string;
    last_name: string;
}

Solution #1: Use Omit

Omit accepts 2 arguments. The first argument is the interface or type you want to create from, and the second argument is the key fields you want to remove.

Let’s look at an example:


interface User {
    id: string;
    first_name: string;
    last_name: string;
}

// Remove a single key field
type MyType1 = Omit<User, 'id'>

// Remove multiple key fields
type MyType2 = Omit<User, 'id' | 'first_name'>

MyType1 has cloned the interface User but has removed the id field.

MyType2 has removed multiple key fields from the interface by using the pipe symbol (|).

If you want to extend an interface but also remove a field from the original interface, this is how you would do it:


interface MyInterface extends Omit<User, 'id'> {
    hair_color: string;
}

const x: MyInterface = {
    first_name: 'Ruben',
    last_name: 'Leija',
    hair_color: 'brown'
}

Solution #2: Use Pick

An alternative solution to using Omit is using the Pick keyword in TypeScript.

Unlike Omit where you’re picking which to exclude from the interface, you can use Pick to pick which key fields you’d like to keep.

This is most helpful when you run into an interface with a lot of key fields. Let’s look at an example how to use Pick.


interface User {
    id: string;
    first_name: string;
    last_name: string;
}

// Picking multiple fields
type MyType1 = Pick<User, 'first_name' | 'last_name'>

You can pick 1 more fields from the interface by using the pipe symbol (|)

And if you’d like to extend an interface by using Pick, you can do something like this:


interface MyInterface extends Pick<User, 'id'> {
    full_name: string;
}

In the example above, I’m picking 1 field from the interface and adding another field called full_name

I like to tweet about and post helpful code snippets. Follow me there if you would like some too!