打字脚本>3.5
TypeScript 3.5引入了Omit helper类型,它创建了一个新类型,其中包含从原始类型中删除的一些属性.docs人中的例子:
type Person = {
name: string;
age: number;
location: string;
};
type QuantumPerson = Omit<Person, "location">;
// equivalent to
type QuantumPerson = {
name: string;
age: number;
};
Thanks to 100 for the update on Typescript 3.5!
打字脚本>2.8
这可以使用Typescript 2.1和2.8中引入的Pick
和Exclude
类型来实现:
/**
* From T pick a set of properties K
*/
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
/**
* Exclude from T those types that are assignable to U
*/
type Exclude<T, U> = T extends U ? never : T;
使用这些类型定义,您可以构造Omit<T,K>
以从泛型类型中省略特定属性:
/**
* From T pick all properties except the set of properties K
*/
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
要说明Typescript中不包含此类型的原因,请执行以下操作:
我们没有包括省略类型,因为它写得很简单
虽然Typescript中没有包含它,但有几个库提供了自己的similar Omit
类型,包括react-redux或Material-UI.
Here is a working example:
interface X {
x1: string;
x2: string;
}
type Y = Omit<X, 'x2'>;
let x: X = {
x1: 'string1',
x2: 'string2'
}
let y: Y = {
x1: 'string1'
}
请注意,将选中要排除的属性,排除未在指定类型中定义的属性是错误的: