简体   繁体   English

枚举到字符串查找对象->没有索引签名

[英]Enum to String Lookup Object -> has no index Signature

I'm trying to map an enum to a String: 我正在尝试将枚举映射到字符串:

enum Status {
    NEW = "NEW",
    INPROCESSING = "IN PROCESSING",
    DONE = "DONE"
};

const statusToColor: { [key in Status ]: string } = {
    "NEW": "blue",
    "IN PROCESSING": "yellow",
    "DONE": "green"
}

Up to this point everything is fine. 到目前为止,一切都很好。 But when I try: 但是当我尝试:

EDIT: Seems as I simplified the problem to much, as the actual problem still seems to be somewhere else: 编辑:似乎我将问题简化了很多,因为实际问题似乎仍然存在于其他地方:

The has no Index error only occurs, when I try to feed "statusToColor" from an Array, like this: 当我尝试从数组中馈送“ statusToColor”时,只会发生没有索引错误,如下所示:

const statusArrayToColors = (statusArray: Status[]): string[] => {
    return statusArray.map(status => statusToColor[status])
}

In this case 在这种情况下

statusToColor[status]

has no Index signature according to the compiler. 根据编译器,没有索引签名。

Your code has a typo. 您的代码有错字。 This works for me Version 2.5.0-dev.20170629 : 这适用于我Version 2.5.0-dev.20170629

enum Status {
    NEW = "NEW",
    INPROCESSING = "IN PROCESSING",
    DONE = "DONE"
};

const statusToColor: { [key in Status ]: string } = {
    "NEW": "blue",
    "IN PROCESSING": "yellow",
    "DONE": "green"
}

const color: string = statusToColor[Status.NEW];

Check the line of statusToColor . 检查statusToColor行。 To define the type you must use colon : , not equal = . 要定义类型,必须使用冒号: ,不等于=

Note: you need at least typescript version 2.4. 注意: 您至少需要打字稿版本2.4。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 字符串枚举的查找对象“没有索引签名” - Lookup object for string enum “has no index signature” 元素隐式地具有“ any”类型,因为类型…在访问键为枚举的对象时没有索引签名 - Element implicitly has an 'any' type because type … has no index signature when accessing the object which key is an enum Map<string, enum> 不可分配给类型 { [key: string]: enum }'。 “地图”类型中缺少索引签名<string, enum> '</string,></string,> - Map<string, enum> is not assignable to type { [key: string]: enum }'. Index signature is missing in type 'Map<string, enum>' 打字稿对象语法问题(无索引签名) - Typescript Object Syntax Question (has no index signature) TypeScript:尝试访问枚举时,没有带有“字符串”类型参数的索引签名 - TypeScript: No index signature with a parameter of type 'string' when try to access the Enum Object 解构:字符串没有匹配的索引签名 - Object Destructuring: no matching index signature for string 输入'字符串| AddressInfo' 没有属性 'port' 也没有字符串索引签名 - Type 'string | AddressInfo' has no property 'port' and no string index signature TypeScript Index对象类型的签名隐式具有类型any - TypeScript Index Signature of object type implicitly has type any TypeScript:对象类型的索引签名隐式具有“任何”类型 - TypeScript: Index signature of object type implicitly has an 'any' type 类型没有与类型“字符串”匹配的索引签名。(2537) - Type has no matching index signature for type 'string'.(2537)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM