泛型变量 / 类型变量

  1. // 函数泛型注解
  2. function identify<T>(arg: T): T {
  3. return arg;
  4. }
  5. identify<number>(333);
  6. // 实际 ts 是可以推断出来的
  7. identify(333);
  8. let a: <T>(arg: T) => T = identify;
  9. // 也可以用对象字面量的方式来定义泛型类型
  10. let a: {<T>(arg:T): T} = identify;
  11. // 接口可以描述对象的形状,那么就可以抽离出一个interface
  12. interface IIdentify {
  13. <T>(arg: T): T
  14. }
  15. let a: IIdentify = identify;

泛型类

  1. class CounterNum<T> {
  2. initialNum: T;
  3. add(x: T, y: T) => T;
  4. }
  5. let counterNum = new CounterNum<number>();
  6. counterNum.initialNum = 0;
  7. counterNum.add(x, y) => {return x + y;};

泛型约束

  1. interface LengthWide {
  2. length: number
  3. }
  4. // 在这里继承了 LengthWide 接口,下面的打印就不会报错了
  5. function fn<T extends LengthWide> (arg: T): T {
  6. console.log(arg.length); // 报错 如果没有约束泛型类型,就不存在length属性
  7. return arg;
  8. }

交叉类型

  1. interface Sentence {
  2. title: string;
  3. content: string;
  4. }
  5. interface Url {
  6. url: string;
  7. }
  8. class Music<T extends Sentence & Url> {
  9. props: T;
  10. constructor (arg: T) {
  11. this.props = arg;
  12. }
  13. info (): T {
  14. return {
  15. url: this.props.url,
  16. title: this.props.title,
  17. content: this.props.content
  18. }
  19. }
  20. }

元组 Tuple

元祖类型允许描述一个已知元素数量和类型的数组。
给元祖越界的时候,元素类型必须为联合类型。

  1. let arr = [string, number];
  2. arr = ["hello", 0]; // ok
  3. arr = [0, "hello"]; // error
  4. arr.push("world"); // ok
  5. arr.push(false); // error boolean 不是( string | number )类型;
  6. let arr1 = [string, number, boolean?]; // 可选元素类型
  7. arr1 = ["a", 1, false]; // ok
  8. arr1 = ["b", 2]; // ok

枚举

可以定义一些带有名字的常量。
也可以通过枚举的属性来访问枚举的成员,和枚举的名字来访问枚举类型。

  1. enum Direction {
  2. Up,
  3. Down,
  4. Left,
  5. Right
  6. }
  7. // 当我们没有定义值时,默认是数字,且自增长
  8. console.log(Direction.Up); // -> 0
  9. console.log(Direction.Down); // -> 1
  10. console.log(Direction.Left); // -> 2
  11. console.log(Direction.Right);// -> 3
  12. enum Direction {
  13. Up = 1,
  14. Down,
  15. Left,
  16. Right
  17. }
  18. // 当定义了第一个值且为数字时,后面的会依据第一个值自增长
  19. console.log(Direction.Up); // -> 1
  20. console.log(Direction.Down); // -> 2
  21. console.log(Direction.Left); // -> 3
  22. console.log(Direction.Right);// -> 4
  23. enum Response {
  24. No = 0,
  25. Yes = 1
  26. }
  27. function response (msg: Response): void {
  28. // ...
  29. }
  30. response(Response.Yes);