How to exclude property from type in TypeScript?
How to exclude property from type in TypeScript?
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'>;
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.