简体   繁体   English

如何使用 typescript 将计算值分配给枚举

[英]How to assign computed values to enum using typescript

I wanted assign values to enum type.我想为枚举类型赋值。 note:text and text1 are actually coming from different file.注意:text 和 text1 实际上来自不同的文件。

const text = "sample text";
const text1 = "Sample text";

const enum textDisplay{
  text = text;
  text1 = text1;
}

that's not how enum work, you can't assign dynamic values to enum, computed values are not permitted in an enum with string valued members.这不是枚举的工作方式,您不能为枚举分配动态值,在具有字符串值成员的枚举中不允许计算值。

https://www.typescriptlang.org/docs/handbook/enums.html https://www.typescriptlang.org/docs/handbook/enums.html

The enum member is initialized with a constant enum expression.枚举成员使用常量枚举表达式进行初始化。 A constant enum expression is a subset of TypeScript expressions that can be fully evaluated at compile time.常量枚举表达式是 TypeScript 表达式的子集,可以在编译时进行完全评估。 An expression is a constant enum expression if it is:一个表达式是一个常量枚举表达式,如果它是:

  • a literal enum expression (basically a string literal or a numeric literal)文字枚举表达式(基本上是字符串文字或数字文字)

  • a reference to previously defined constant enum member (which can originate from a different enum)对先前定义的常量枚举成员的引用(可以源自不同的枚举)

  • a parenthesized constant enum expression带括号的常量枚举表达式

  • one of the +, -, ~ unary operators applied to constant enum expression +, -, *, /, %, <<, >>, >>>, &, |, ^ binary operators with constant enum expressions as operands应用于常量枚举表达式的 +、-、~ 一元运算符之一 +、-、*、/、%、<<、>>、>>>、&、|、^ 以常量枚举表达式作为操作数的二元运算符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM