Enum keys允许包含空格吗?

huangapple go评论60阅读模式
英文:

Are spaces in enum keys allowed?

问题

以下代码

enum Foo {
Bar = 1,
["Bar Test"] = 3,
}

TS Playground中编译正常,但将其插入到一个干净的create-react-app项目中会产生语法错误:

SyntaxError: <...> s-test\src\App.tsx: Unexpected token (7:2)

这是否是有效的TS?是否有一些tsconfig变量或版本允许它?

英文:

The following code

enum Foo {
  Bar = 1,
  [&quot;Bar Test&quot;] = 3,
}

compiles fine in TS Playground but inserting it into a clean create-react-app project produces a syntax error:

SyntaxError: &lt;...&gt;\ts-test\src\App.tsx: Unexpected token (7:2)

Is this valid TS? Is there some tsconfig variable or version that allows it?

答案1

得分: 1

Spaces are indeed allowed in enum keys; they are not required to be valid identifiers.

This doesn't seem to be explicitly documented anywhere obvious (the outdated spec section on enum declarations does indicate that the key could be any non-computed property name, which may be an identifier, but could also be a string literal).

However, there was a bug reported at microsoft/TypeScript#40152 and fixed at microsoft/TypeScript#40679 whereby enums with keys that were invalid as identifiers were causing the compiler to produce invalid JavaScript (presumably they had just assumed that keys would be valid identifiers). The fix was to change the emitted JavaScript to handle invalid identifier enum keys. That implies that enums with such keys are intentionally supported. Otherwise, the fix would be to make the TypeScript compiler reject such enum keys.

So it's safe to say that these are supported.

英文:

Spaces are indeed allowed in enum keys; they are not required to be valid identifiers.

This doesn't seem to be explicitly documented anywhere obvious (the outdated spec section on enum declarations does indicate that the key could be any non-computed property name, which may be an identifier, but could also be a string literal).

However, there was a bug reported at microsoft/TypeScript#40152 and fixed at microsoft/TypeScript#40679 whereby enums with keys that were invalid as identifiers were causing the compiler to produce invalid JavaScript (presumably they had just assumed that keys would be valid identifiers). The fix was to change the emitted JavaScript to handle invalid identifier enum keys. That implies that enums with such keys are intentionally supported. Otherwise, the fix would be to make the TypeScript compiler reject such enum keys.

So it's safe to say that these are supported.

huangapple
  • 本文由 发表于 2023年5月15日 04:53:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76249626.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定