typescript - TS 枚举中的重复字符串值不会导致编译错误?

标签 typescript typescript-typings tsc

我在 TypeScript 枚举中有这个:

export enum LMXLockRequestError {
  MaxRetries = 'bad_args',
  BadArgumentsError = 'bad_args',
}

这似乎不会导致编译错误。 它转换为:

var LMXLockRequestError;
(function (LMXLockRequestError) {
    LMXLockRequestError["MaxRetries"] = "bad_args";
    LMXLockRequestError["BadArgumentsError"] = "bad_args";
})(LMXLockRequestError = exports.LMXLockRequestError || (exports.LMXLockRequestError = {}));

如果我要用它来做:

if(v === LMXLockRequestError.MaxRetries){

}

如果 v 是 'bad_args',它将同时匹配 MaxRetries 和 BadArgumentsError。

这是应该发生的吗?或者我应该在 Github 上提交 TypeScript 问题吗?

对我来说,枚举应该有不同的键,但不一定有不同的值?如果有一种方法可以告诉枚举它必须具有不同的值,那就太好了。

最佳答案

关于 TS ENUM 规范:

Enums allow us to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

没有任何关于它应该是 uniq 的东西,所以可能这种行为是好的。

enum/typescript

更新: 关于 ENUM 和“错误”还有另一件有趣的事情:

Enum value incrementation does not consider previously defined values, nor does the compiler throws an error on duplicate values.

Which means you can end up with potential bugs:

enum Color {Red = 3, Green = 2, Blue};

Color.Red == Color.Blue; //true

关于typescript - TS 枚举中的重复字符串值不会导致编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51170387/

相关文章:

javascript - TypeScript 是否可以从动态对象推断键?

css - Bootstrap Dropdowns 按钮不适用于 Angular 8 组件

javascript - 使用声明文件中的 npm 包捆绑类型

typescript - 错误 TS2497 : Module '...' resolves to a non-module entity and cannot be imported using this construct

node.js - 无法通过 npm 全局卸载 typescript

html - 如何在单元测试中设置html输入元素的文本内容

typescript - 如何在 typescript 中使用 singleton() 在构造函数中传递值?

typescript - 文字类型推断 - Typescript

typescript - 使用索引访问时如何避免 TS2322 "Type any is not assignable to type never"

node.js - typescript - tsc 如何将其他文件类型复制到 dist 文件夹