Categories
TypeScript Answers

How to exclude property from type with TypeScript?

Spread the love

Sometimes, we want to exclude property from type with TypeScript.

In this article, we’ll look at how to exclude property from type with TypeScript.

How to exclude property from type with TypeScript?

To exclude property from type with TypeScript, we can use the Omit type.

For instance, we write

interface Test {
  a: string;
  b: number;
  c: boolean;
}

type OmitA = Omit<Test, "a">;
type OmitAB = Omit<Test, "a" | "b">;

to create the Test interface.

And then we derive 2 types OmitA and OmitAB from it by using the Omit type.

To create OmitA, we use Omit with Test and 'a' to return a type that only has the b and c properties from Test.

And we create OmitAB that returns a type that has a and b excluded so it only takes property c listed in Test.

Conclusion

To exclude property from type with TypeScript, we can use the Omit type.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *