Generic programming
Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters.
把一个原本特定于某个类型的算法或类当中的类型信息抽掉,抽出来做成模板参数T
function identity( arg: any ): any { return arg; }
We need a way of capturing the type of the argument in such a way that we can also use it to denote what is being returned. Here, we will use a type variable, a special kind of variable that works on types rather than values.
function identity<T>( arg: T ): T { return arg; }
function identity( something: number | string ): number | string { return something; } // Type 'string | number' is not assignable to type 'number'. // Type 'string' is not assignable to type 'number'.(2322) const a: number = identity( 123 ); const b: number = identity( 123 ) as number;
function identity<T>( something: T ): T { return something; } const a: number = identity( 123 ); // Type 'string' is not assignable to type 'number'.(2322) const b: number = identity( 'string' ); const c: string = identity( 'sting' ); // Type 'number' is not assignable to type 'string'.(2322) const d: string = identity( 123 );
function identity<T extends string | number>( something: T ): T { return something; } const a: string = identity( 'string' ); const b: number = identity( 123 ); // Type 'string | number' is not assignable to type 'boolean'. // Type 'string' is not assignable to type 'boolean'.(2322) // Argument of type 'boolean' is not assignable to parameter of type 'string | number'.(2345) const c: boolean = identity( true );