TypeScript Essential Notes 6 - Generics

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值