我正在尝试创建一个省略给定类型中的属性的接口(interface)。为此,我使用了 Omit
这导致 Type 所以它的定义是错误的。但是,如果它不是一个通用接口(interface),它就可以完美地工作。
考虑以下示例。
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 的智能感知显示了非泛型参数的属性列表,但它无法为泛型参数执行此操作。泛型参数被视为任何类型的对象。
我主要担心的是,如果我不应该使用
Omit
我还能用什么?如果我想用类型而不是接口(interface)来实现它,我该怎么做呢?
最佳答案
TypeScript 在你的通用接口(interface)上给你一个错误:
An interface can only extend an object type or intersection of object types with statically known members.
这就是为什么它不起作用。 (参见错误 on the playground。)
您可以改用类型:
type OmitMatch<T extends { match: any }> = Omit<T, "match">;
这工作正常。 (On the playground。)
关于 typescript :从通用接口(interface)中省略属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60586984/