TypeScript 使用枚举类型而不是字符串类型迭代字符串枚举

标签 typescript enums

我在 TypeScript 中有一个字符串枚举,我想像下面这样迭代它。但是,当我这样做时,迭代器的类型是字符串而不是枚举类型。

enum Enum { A = 'a', B = 'b' };

let cipher: { [key in Enum]: string };

for (const letter in Enum) {
    cipher[letter] = 'test'; // error: letter is of type 'string' but needs to be 'Enum'
}

我得到的确切错误是:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: string; b: string; }'.
  No index signature with a parameter of type 'string' was found on type '{ a: string; b: string; }'.ts(7053)

这看起来很奇怪,因为它保证字母是枚举。有什么办法可以解决这个问题吗?

最佳答案

我会将我的评论作为答案发布,这样问题就不会无人问津。

cipher 的类型将 key 作为Enum 的值,即:

let cipher: {
  a: string;
  b: string;
}

因为您使用的是字符串枚举。但是当使用 for...in 迭代时,您迭代生成对象的可枚举属性,这些属性是 ['A', 'B'] 因为生成的对象(TypeScript v4) 将是:

var Enum;
(function (Enum) {
    Enum["A"] = "a";
    Enum["B"] = "b";
})(Enum || (Enum = {}));

因此您需要迭代枚举值。 为此,您可以使用 Object.values 获取其值的数组,并使用 for...of 对其进行迭代。这样,letter 类型将是 Enum

for (const letter of Object.values(Enum)) {
    cipher[letter] = 'test'; // error: letter is of type 'string' but needs to be 'Enum'
}

我以前从未将 for...in 与枚举一起使用,但我希望编译器有足够的信息,所以 for...in 严格类型 letter"A"| 的并集"B" 但它似乎将类型扩展为 string

关于TypeScript 使用枚举类型而不是字符串类型迭代字符串枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67029237/

相关文章:

Angular 6 with NGRX 获得 "You provided ' undefined',其中预期有流。在调度时”

typescript - TS4.1 : Is there a way to define this property path type that isn't excessively deep?

c++ - 在类中添加枚举定义会破坏其二进制向后兼容性吗?

ios - 如何在头文件中声明公共(public) NS_Enum 属性

javascript - Typescript 泛型未返回正确的类型

typescript - 如何在不求助于 'any' 的情况下键入此函数

c++ - C++如何衰减强类型枚举?

ios - 无法在 Objective-C 中将 Swift 类与枚举一起使用

python - 如何在 Python 中实现以下 C 代码? (typedef、枚举和开关)

javascript - 如何从 for 循环返回解析 Promise Like 对象