interface I {
a: number;
}
interface II extends I {
b: number;
}
function f(arg: I) : void {
// do something with arg without trimming the extra properties (logical error)
console.log(arg);
}
const obj: II = { a:4, b:3 };
f(obj);
我想要做的是使函数 f
只接受 I
类型的对象,而不接受 II
类型或任何其他派生接口(interface)
最佳答案
由于 typescript 的工作方式而困难。您可以做的就是向基础添加一个 type
字段,派生接口(interface)将覆盖该字段。然后将函数限制为仅显式接受基数:
interface IFoo<T extends string = "foo"> {
type: T;
}
interface IBar extends IFoo<"bar"> {
}
function ray(baseOnly: IFoo<"foo">) {
}
let foo: IFoo = { type: "foo" };
let bar: IBar = { type: "bar" };
ray(foo); // OK!
ray(bar); // error
输出错误:
[ts]
Argument of type 'IBar' is not assignable to parameter of type 'IFoo<"foo">'.
Types of property 'type' are incompatible.
Type '"bar"' is not assignable to type '"foo"'.
关于validation - Typescript:声明采用精确接口(interface)类型参数的函数,而不是其派生类型之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46145368/