function hello<T>(arg: T): T {return arg;}const output = hello<string>("hello world");const output = hello<string>(10); // 错误的 已经指定泛型是固定的string类型
通过
在使用的时候指定函数是一个字符串类型或者其他类型。
泛型应用
function hello<T> (num: T): T {console.log(num.length); // 错误的 num是没有类型的,也就没有length属性return num;}
这样的情况下我们有些时候写代码就被限制死了,是不行的。
function hello<T> (num: T[]): T[] {console.log(num.length); // 可以的,num的类型是被指定了数组, 数组是由length属性的return num;}const list:Array<string> = hello<String>(["1","2","3"]);
泛型类型
function hello<T>(arg: T): T {return arg;}const myHello:<K>(arg: K) => K = hello; // 拉姆达表达式// const myHello:{<T>(arg: T): T} = hello; 这个等同于拉姆达表达式 结果是一样的myHello("hello"); // 这样就能指定函数泛型
interface Hello {<T>(arg: T): T;}function myHello<T> (arg: T): T {return arg;}const mh:Hello = myHello;console.log(mh<string>("hello")); // 指定泛型 但是这样很不方便/*-------------------------------------------------------------*/interface Hello<T> {(arg: T): T;}function myHello<T> (arg: T): T {return arg;}const mh:Hello<number> = myHello; // 这样指定泛型更加简单console.log(mh(100));
泛型类
class HelloNumber<T> {ten: T;add(x: T, Y: T) => T;}const myHello = new HelloNumber<number>(); // 不一定是number 可以是其他数据类型myHello.ten = 10;myHello.add = function(x, y){return x + y;}console.log(myHello.ten); // 10;console.log(myHello.add(1, 2)); // 3
