我正在尝试创建一个接口,该接口忽略给定类型的属性。为此,我使用了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
,我还能使用什么?如果我想用类型而不是接口来实现它,那我该怎么做?
答案 0 :(得分:2)
TypeScript在通用接口上给您一个错误:
接口只能扩展对象类型或具有静态已知成员的对象类型的交集。
这就是为什么它不起作用的原因。 (请参见错误on the playground。)
您可以改用一种类型:
type OmitMatch<T extends { match: any }> = Omit<T, "match">;
那正常工作。 (On the playground。)