泛型函数
function identify<T>(arg:T): T {
return arg;
}
使用
let output = identify<string>("myString");
let op = identify("mystring");// 让编译器推断类型
数组
function logging<T>(arg:T[ ]) :T [ ]{
...
}
function loging2<T> (arg:Array<T>):Array<T> {
...
}
类
class GenericNUmber<T>{
zearoV:T;
add:(x:T,y:T)=>T;
}
泛型约束
function copyFields<T extends U, U>(target: T, source: U): T {
for (let id in source) {
target[id] = source[id];
}
return target;
}
let x = { a: 1, b: 2, c: 3, d: 4 };
getProperty(x, "a"); // okay
getProperty(x, "m"); // error: Argument of type 'm' isn't assignable to 'a' | 'b' | 'c' | 'd'.