使用接口作为枚举

Use interface as enum

我平时的做法是这样的:

enum tmp {
  a,
  b
}

const doStuff = (val: tmp) => {
  console.log(val);
}

doStuff(tmp.b); // logs 1

但是我使用的库是这样的:

interface tmpMap {
  a: 0;
  b: 1;
}

const tmp: tmpMap;

所以我尝试这样做:

const doStuff = (val: tmpMap) => {
  console.log(val);
}

doStuff(tmp.b);

但这会引发一堆错误,而且根本不起作用。

Variable 'tmp' is used before being assigned.

Argument of type 'number' is not assignable to parameter of type 'tmpMap'.

这是一个 link 去游乐场的路线。

有没有办法像枚举设置一样使用此设置?

Playground

interface tmpMap {
  a: 0;
  b: 1;
}

// You'll have to actually assign the constant
declare const tmp: tmpMap;

const doStuff = (val: tmpMap[keyof tmpMap]) => {
  console.log(val);
}

doStuff(tmp.b);