[英]Typescript generic constraints on type parameters class
How can you put a constraint on a TypeScript type parameter. 如何对TypeScript类型参数设置约束。 In c# you can use the construct
{ where T:class}
? 在c#中你可以使用构造
{ where T:class}
?
Does Typescript support constraints on type parameters like c# { where T:class}.
Typescript是否支持对类型参数的约束,例如c#{where T:class}。
Yes. 是。 Syntax is of the form
<T extends SomeClass>
instead of <T>
语法的形式为
<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
Note that types in typescript are structural ( why ) which means that classes and interfaces are handled the same way as far as the generic constraint is concerned. 请注意,typescript中的类型是结构的( 为什么 ),这意味着类和接口的处理方式与泛型约束相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.