How to exclude property ...
How to exclude property ...
In TypeScript, excluding properties from types is a common task that can be achieved using various methods, primarily through utility types such as Omit
. Below, I'll explain the primary methods to exclude properties from types in TypeScript, focusing on the Omit
utility type, along with other relevant techniques.
Omit
Utility TypeThe Omit
utility type is one of the most straightforward and commonly used methods to exclude properties from a type. It creates a new type by omitting the specified keys from an existing type.
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
T
is the original type from which properties are to be omitted.K
is the union type of the keys (property names) to be omitted from T
.Suppose you have a User
type and you want to create a new type that excludes the password
property:
interface User {
id: number;
name: string;
password: string;
}
type UserWithoutPassword = Omit<User, 'password'>;
const user: UserWithoutPassword = {
id: 1,
name: 'John Doe'
// password is not included here
};
In this example, UserWithoutPassword
is a new type identical to User
but without the password
property[7][12].
You can also create custom types that exclude properties by combining mapped types with conditional types:
type ExcludeProperty<T, K extends keyof T> = {
[P in keyof T as Exclude<P, K>]: T[P]
};
type UserWithoutPassword = ExcludeProperty<User, 'password'>;
This method involves more complex type manipulation but offers flexibility for more advanced scenarios[2].
Another less common approach involves using intersection types combined with types where the excluded property is set to never
:
type User = {
id: number;
name: string;
password: string;
};
type ExcludePassword = {
...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào