类型参数类的Typescript通用约束

塔鲁纳河

如何对TypeScript类型参数施加约束。在C#中可以使用构造{ where T:class}

巴沙尔

Typescript是否支持对类型参数的约束,例如c#{where T:class}。

是。语法的形式<T extends SomeClass>而不是<T>

interface Foo{
    foo: number;
}

function foo<T extends Foo>(foo:T){
    console.log(foo.foo);
}

foo({foo:123}); // okay
foo({foo:'123'}); // Error

请注意,打字稿中的类型是结构性的(为什么),这意味着就泛型约束而言,类和接口的处理方式相同。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章