Introducing generics
定义泛型函数
The syntax for defining a generic function is pretty straightforward. You simply add the greater than and less than signs right after the function name, but before the parenthesis圆括号 containing the parameter list and then give your generic type parameter a name like this.
function clone<T>(value: T): T {
let serialized = JSON.stringify(value);
return JSON.parse(serialized);
}
clone("Hello");
clone(123);
clone({ name: "Bob" });
Creating generic classes
var array: number[] = [1, 2, 3];
var array2: Array<number> = [1, 2, 3];
// they are completely functionally equivalent 它们在功能上完全等效
泛型类
class KeyValuePair<TKey, TValue> {
constructor(public key: TKey, public value: TValue) {}
}
let pair1 = new KeyValuePair<number, string>(1, "First");
// Oddly enough, the Javascript date.now function doesn't actually return a date object.
// It returns the number of milliseconds elapsed since January 1, 1970.
let pair2 = new KeyValuePair<string, number>("Second", Date.now()); //
let pair3 = new KeyValuePair(3, "Third"); //也可以省略类型,TS自行推断
class KeyValuePairPrinter<T, U> {
constructor(private pairs: KeyValuePair<T, U>[]) {}
print() {
for (const p of this.pairs) {
console.log(`${p.key}:${p.value}`);
}
}
}
var printer = new KeyValuePairPrinter([pair1, pair3]);
Applying generic constraints
泛型约束
For example, before I just added the generic type parameter to the totalLength method, it only accepted objects that had a length field 长度字段 field 字段.
To apply that same constraint to the generic type parameter, I simply use that same anonymous type匿名类型.
// 约束类型extends匿名类型
function totalLength<T extends { length: number }>(x: T, y: T): number {
var total: number = x.length + y.length;
return total;
}
var length = totalLength("addf", "dfdf");
caveat警告
// They can be any type that is compatible with type T,
// including those types that inherit from it.
class CustomArray<T> extends Array<T> {}
var length1 = totalLength([1, 2], new CustomArray<number>(1, 2));
Used in the right way on the right problems, generic functons and classes can really elevate提高 your code from good to elegant.