我有两个接口,X和Y.X有2个属性,x1和x2.现在Y想继承X而不想x2继承.
interface X {
x1 : string;
x2 : string;
}
interface Y extends X{
// x2 shouldn't be available here
}
Run Code Online (Sandbox Code Playgroud)
作为新的TypeScript,我无法弄清楚.是否有任何extends X without x1类型的内置功能TypeScript?
注意:在我的实际情况中,X是一个内置的interface.所以,我需要在不改变X界面的情况下这样做.可能吗 ?
sn4*_*n42 17
这可以使用Typescript 2.1和2.8中引入的Pick和Exclude类型来实现:
type Person = {
name: string;
age: number;
location: string;
};
type QuantumPerson = Omit<Person, "location">;
// equivalent to
type QuantumPerson = {
name: string;
age: number;
};
Run Code Online (Sandbox Code Playgroud)
使用这些类型定义,您可以构造Omit<T,K>以从泛型类型中省略特定属性:
/**
* 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;
Run Code Online (Sandbox Code Playgroud)
要说明Typescript 2.8发行说明为什么此类型不包含在Typescript中:
我们没有包含Omit类型,因为它简单地写为
Pick<T, Exclude<keyof T, K>>.
虽然它没有包含在Typescript中,但是几个库提供了它们自己相似的 Omit类型,包括react-redux或Material-UI.
这是一个工作示例:
/**
* 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>>;
Run Code Online (Sandbox Code Playgroud)
请注意,将检查要排除的属性,排除未在指定类型中定义的属性是错误的:
| 归档时间: |
|
| 查看次数: |
4440 次 |
| 最近记录: |