Some objects, like JavaScript’s Date object, can be called with or without new You can combine call and construct signatrues in the same type arbitarily.
1 2 3 4
interfaceCallOrConstruct { new (s: string): Date; (n?: number): number; }
Generic Functions 通用函数
In TypeScript, generics are used when we want to describe a correspondence between two values. We do this by declaring a type parameter in function signature.
1 2 3 4 5 6 7 8 9 10 11
function firstElement<Type>(arr: Type[]): Type | undefined { return arr[0]; }
function map<Input, Output>(arr: Input[], func: (arg: Input) =>Output) { return arr.map(func); } // Parameter 'n' is of type 'string' // 'parsed' is of type 'number[]' const parsed = map(["1", "2", "3"], (n) =>parseInt(n));
When we need a length property that’s a number. We constrain the type parameter to that type by writing an extends clause:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
function longest<Typeextends { length: number }>(a: Type, b: Type) { if (a.length >= b.length) { return a; } else { return b; } }