TypeScript字符串枚举

2019-05-21107次阅读TypeScript

先看一个简单的 TypeScript 枚举类型:

enum Tristate {
  False,
  True,
  Unknown
}

编译成 JavaScript:

var Tristate;
(function(Tristate) {
  Tristate[(Tristate['False'] = 0)] = 'False';
  Tristate[(Tristate['True'] = 1)] = 'True';
  Tristate[(Tristate['Unknown'] = 2)] = 'Unknown';
})(Tristate || (Tristate = {}));

TypeScript字符串枚举提供有意义/可调试的字符串。因些它还可以用于简单的字符串比较。

export enum EvidenceTypeEnum {
  UNKNOWN = '',
  PASSPORT_VISA = 'passport_visa',
  PASSPORT = 'passport',
  SIGHTED_STUDENT_CARD = 'sighted_tertiary_edu_id',
  SIGHTED_KEYPASS_CARD = 'sighted_keypass_card',
  SIGHTED_PROOF_OF_AGE_CARD = 'sighted_proof_of_age_card'
}
// Where `someStringFromBackend` will be '' | 'passport_visa' | 'passport' ... etc.
const value = someStringFromBackend as EvidenceTypeEnum;

// Sample use in code
if (value === EvidenceTypeEnum.PASSPORT) {
  console.log('You provided a passport');
  console.log(value); // `passport`
}

详细了解TypeScript枚举

上一篇: Sass中&符以及Sass变量使用  下一篇: inputmode输入模式了解一下  

TypeScript字符串枚举相关文章