英文:
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,
["Bar Test"] = 3,
}
compiles fine in TS Playground but inserting it into a clean create-react-app project produces a syntax error:
SyntaxError: <...>\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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论