泛型函数
function identity<T>(arg: T): T {return arg;}// 使用方式let output = identity<string>("myString"); // type of output will be 'string'let output = identity("myString"); // type of output will be 'string'
多个类型参数
function swap<T, U>(tuple: [T, U]): [U, T] {return [tuple[1], tuple[0]];}swap([7, 'seven']); // ['seven', 7]
泛型变量
function loggingIdentity<T>(arg: T[]): T[] {console.log(arg.length); // Array has a .length, so no more errorreturn arg;}
你可以这样理解loggingIdentity的类型:泛型函数loggingIdentity,接收类型参数T和参数arg,它是个元素类型是T的数组,并返回元素类型是T的数组。 如果我们传入数字数组,将返回一个数字数组,因为此时T的的类型为number。 这可以让我们把泛型变量T当做类型的一部分使用,而不是整个类型,增加了灵活性
泛型接口
interface GenericIdentityFn<T> {(arg: T): T;}function identity<T>(arg: T): T {return arg;}let myIdentity: GenericIdentityFn<number> = identity;
泛型类
泛型类指的是实例部分的泛型,类的静态属性不能使用这个泛型类型
泛型约束
在函数内部使用泛型变量的时候,由于事先不知道它是哪种类型,所以不能随意操作它的属性或方法
interface Lengthwise {length: number;}function loggingIdentity<T extends Lengthwise>(arg: T): T {console.log(arg.length); // Now we know it has a .length property, so no more errorreturn arg;}// 我们需要传入符合约束类型的值,必须包含必须的属性:loggingIdentity({length: 10, value: 3});
在泛型约束中使用类型参数
可以声明一个类型参数,且被另一个类型参数所约束
function getProperty<T, K extends keyof T>(obj: T, key: K) {return obj[key];}let x = { a: 1, b: 2, c: 3, d: 4 };getProperty(x, "a"); // okaygetProperty(x, "m"); // error: Argument of type 'm' isn't assignable to 'a' | 'b' | 'c' | 'd'.
泛型参数的默认类型
在 TypeScript 2.3 以后,我们可以为泛型中的类型参数指定默认类型。当使用泛型时没有在代码中直接指定类型参数,从实际值参数中也无法推测出时,这个默认类型就会起作用
declare function create<T extends HTMLElement = HTMLDivElement, U = T[]>(element?: T,children?: U): Container<T, U>;
