validation - Typescript:声明采用精确接口(interface)类型参数的函数,而不是其派生类型之一

标签 validation typescript inheritance interface

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/

相关文章:

node.js - 如何使用 Jade 模板将 block append 到父级

c++ - 输入字符时忽略回车键

javascript - 如何在 Joi 中的值上验证具有两个最大条件的对象?

angular - 条件@HostBinding 取决于@Input()

string - Typescript 类型 'string' 不可分配给类型 'never' 。错误

ruby-on-rails - 单表继承查找问题

Java正则表达式检查字符串是否是有效的数字格式(逗号和小数点放置)

c# - Enterprise Library 6 验证不是从配置中读取?

unit-testing - 在没有导出的情况下测试 typescript 模块

Python属性描述符设计: why copy rather than mutate?