简体   繁体   中英

Advantage of TypeScript generics

I'm new here and have a question: What are the advantages of using generics in 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.8.x:

var myArray : String[];


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.

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:

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

Rather than having to have:

interface Array {
    pop() : any;
}

Or (for each type)

interface ArrayOfStrings {
    pop() : string;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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