【问题标题】:How to specify type of index of enum in typescript如何在打字稿中指定枚举索引的类型
【发布时间】:2021-06-02 01:34:03
【问题描述】:

考虑以下示例:

enum Color {
    Green = "green",
    Red = "red"

}

let index : keyof Color
index = "Green" 

console.log(Color[index])

错误

Type '"Green"' is not assignable to type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | ... 27 more ... | "padEnd"'.
Element implicitly has an 'any' type because expression of type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | ... 27 more ... | "padEnd"' can't be used to index type 'typeof Color'. No index signature with a parameter of type 'number' was found on type 'typeof Color'.

索引变量必须是枚举颜色键的字符串版本。 如何指定索引变量的类型?

【问题讨论】:

  • 也许:let index : keyof typeof Color

标签: javascript typescript


【解决方案1】:

您应该使用let index: keyof typeof Color,因为Color 实际上是一个对象(某种字典),所以您需要首先使用typeof 获取它的类型。要深入了解 keyoftypeof 的作用,请参阅 an excellent question and thread that explains it

enum Color {
    Green = "green",
    Red = "red"

}

let index: keyof typeof Color;
index = "Green" 

console.log(Color[index])

请参阅TypeScript Playground 上的工作示例。

【讨论】:

    猜你喜欢
    • 2019-03-13
    • 2020-04-14
    • 2021-10-03
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    相关资源
    最近更新 更多