简体   繁体   English

TypeScript泛型的优势

[英]Advantage of TypeScript generics

I'm new here and have a question: What are the advantages of using generics in TypeScript. 我是新来的,并且有一个问题:在TypeScript中使用泛型有什么优点。

msdn on the TypeScript 0.9 update: http://blogs.msdn.com/b/typescript/archive/2013/03/25/working-on-typescript-0-9-generics-overload-on-constants-and-compiler-performance.aspx 关于TypeScript 0.9更新的msdn: http : //blogs.msdn.com/b/typescript/archive/2013/03/25/working-on-typescript-0-9-generics-overload-on-constants-and-compiler -performance.aspx

TypeScript 0.8.x: TypeScript 0.8.x:

var myArray : String[];


TypeScript 0.9.x: TypeScript 0.9.x:

var myArray : Array<String>;

Does it have to do with increased type safety or something like that? 它是否与增加类型安全性有关?

The advantage for generics on Arrays is "under the hood". 数组上泛型的优势是“幕后”。 Both annotations in your question are identical as far as TypeScript is concerned. 就TypeScript而言,问题中的两个注释均相同。

The advantage of generics is that you can reuse code, rather than copy and pasting the code to work for different types or using a dynamic type where you don't intend to use dynamic behaviour. 泛型的优点是您可以重用代码,而不是复制和粘贴代码以使其适用于不同类型或在不打算使用动态行为的情况下使用动态类型。

For example, the Array interface can be declared just once: 例如,可以仅一次声明Array接口:

interface Array<T> {
    pop() : T;
}

Rather than having to have: 不必拥有:

interface Array {
    pop() : any;
}

Or (for each type) 或(每种类型)

interface ArrayOfStrings {
    pop() : string;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM