枚举的应用

TypeScript的枚举怎么用?

展示TypeScript中的枚举(enum)的一种实际用例。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class P {
  x: number;
  y: number;
  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
}
enum key {
  x = "x",
  y = "y",
}

const p0 = new P(1, 2);

function dosomething(key: key) {
  console.log(p0[key])
}

dosomething('x');
dosomething('y');
updatedupdated2020-10-122020-10-12