Typescript:从通用接口省略属性

问题描述 投票:0回答:1

我正在尝试创建一个接口,该接口忽略给定类型的属性。为此,我使用了Omit,其结果为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
}

在此示例中,VSCode的intelliSense显示了非泛型参数的属性列表,但对于泛型参数则无法执行。通用参数被视为任何类型的对象。

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

typescript interface typescript-typings extends typescript-generics
1个回答
2
投票

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

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

这就是为什么它不起作用。 (请参见错误on the playground。)

您可以改用我们的类型:

type OmitMatch<T extends { match: any }> = Omit<T, "match">;

这正常工作。 (On the playground。)

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.