Typescript Const枚举索引签名

时间:2017-10-02 03:09:47

标签: typescript



export const enum Outcome {
  primary = 'primary',
  success = 'success',
  failure = 'failure'
}

export const buttonColors: { [key in Outcome]: string } = { primary: '#007aff', success: '#00C260', failure: '#F56B62' };

// example 1
buttonColors[Outcome.primary]; // works

// example 2 - interface doesn't work

interface IProps {
  outcome: Outcome;
}

const first: IProps = { outcome: Outcome.primary };
buttonColors[first.outcome]; // Error: Element implicitly has an 'any' type because type '{ primary: string; success: string; failure: string; }' has no index signature.

// example 3 - class - works
class Props {
  // notice this is class
  outcome: Outcome;
}

const second: Props = new Props();
second.outcome = Outcome.primary;
buttonColors[second.outcome]; // works




在上述所有情况下,const enum用于访问buttonColors,但不确定访问何时通过。一个界面,它不起作用。

感谢任何帮助。

谢谢,

0 个答案:

没有答案