打字稿:从通用接口中省略属性

Ham*_*eli 4 extends interface typescript typescript-generics typescript-typings

我正在尝试创建一个省略给定类型的属性的接口。为此,我使用Omitwhich 结果在 Type 所以它的定义是错误的。但是,如果它不是通用接口,它就可以完美运行。

考虑以下示例。

interface IBaseType {
  prop1: number;
  prop2: string;
  match: boolean;
}

interface OmitMatchNoGeneric extends Omit<IBaseType, "match"> {}

interface OmitMatch<T extends { match: any }> extends Omit<T, "match"> {}

function test(genericArg: OmitMatch<IBaseType>, nonGenericArg: OmitMatchNoGeneric) {
  nonGenericArg.prop1 = 5; // the properties are suggested
  genericArg.prop1 = 5; // intelliSense fails to list the properties
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,VSCode 的智能感知显示了非泛型参数的属性列表,但它没有为泛型参数显示。泛型参数被视为 any 类型的对象。

我主要关心的是,如果我不应该使用,Omit我还能使用什么?如果我想用类型而不是接口来实现它,我该怎么做?

T.J*_*der 5

TypeScript 在你的通用接口上给你一个错误:

接口只能扩展对象类型或对象类型与静态已知成员的交集。

这就是它不起作用的原因。(请参阅操场上的错误。)

您可以使用我们的类型:

type OmitMatch<T extends { match: any }> = Omit<T, "match">;
Run Code Online (Sandbox Code Playgroud)

这工作正常。(在操场上。)