What is the use of Omit<T, K> in TypeScript?
When learning Nestjs, I often came across the usage of Omit<XXXEntity,'xxx'>
in Repository with TS. Since I had never used it before and didn't know what it meant, I just copied it directly from the tutorial.
But it appeared so frequently that I felt the need to dig deeper. I couldn't keep writing without understanding what I was doing. So I decided to look into the source code to see what it actually is.
Let's start with the conclusion:
The purpose of Omit<T, K> is to create a new type that excludes the specified properties K from the type T.
Let's take a look at this code:
type Omit<T, K extends string | number | symbol> = {
[P in Exclude<keyof T, K>]: T[P];
};
- T is the original type, representing the type of the object to be operated on.
- K is a union type, representing the type of properties to be excluded from T.
First, keyof T
is an index type query, which returns a union type of all property names of type T.
Then, Exclude<keyof T, K>
is used to exclude the properties of type K from keyof T
, returning a union type of property names that exclude the type K.
Finally, using the mapping type syntax [P in Exclude<keyof T, K>]: T[P]
, we create a new type that includes all properties of T except for property K, and the property types are the same as the corresponding properties in the original type T.
In short, the Omit<T, K> type can be used to create a new type that excludes the specified properties K from the original type T.
For example, let's say we have a type Person:
type Person = {
name: string;
age: number;
email: string;
};
We can use the Omit type to create a new type PersonWithoutEmail, which excludes the email property from the Person type:
type PersonWithoutEmail = Omit<Person, 'email'>;
In this way, the PersonWithoutEmail type will only contain the name and age properties, without the email property.
const person: PersonWithoutEmail = {
name: 'John',
age: 30,
};
By using the Omit type, we can conveniently create a new type that excludes the specified properties from the original type.