如何在继承时从接口中排除属性

the*_*e64 7 typescript

我有两个接口,XY.X有2个属性,x1x2.现在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中引入的PickExclude类型来实现:

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-reduxMaterial-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)

省略的例子

请注意,将检查要排除的属性,排除未在指定类型中定义的属性是错误的:

使用不存在的属性名称省略的示例

  • @ theapache64感谢您的评论,修改后的版本也可以在`@ material-ui/core`中使用,它很容易实现.使用您喜欢的任何版本. (2认同)
  • 显然 Typescript 态度软化了,他们从 3.5.1 开始添加了 Omit:https://devblogs.microsoft.com/typescript/announcing-typescript-3-5/#the-omit-helper-type。 (2认同)