【发布时间】:2021-08-20 05:35:12
【问题描述】:
在 Typescript 中我定义了一个接口:
interface IPriority {
KEY1: number;
KEY2: number;
KEY3: number;
DEFAULT: number;
}
我将IPriority 类型的对象传递给函数,如下所示:
class Foo {
async someFunction(priority: IPriority) {
const someMap: Map<string, string> = new Map();
//someMap has been properly initialized and has valid data
const key = someMap.get("KEY1") ?? "KEY1";
//const key = "KEY1";
if(key) {
const temp = priority[key];
console.log(temp);
}
}
}
这样做,我得到这个错误:Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IPriority'. No index signature with a parameter of type 'string' was found on type 'IPriority'.。
如果我将const temp = priority[key]; 更改为此const temp = priority.get(key),我会收到此错误:Property 'get' does not exist on type 'IPriority'.
如何使用 get 方法或对象索引语法 (priority[key]) 访问 KEY1、KEY2、... 的值?
这是code的链接
【问题讨论】:
-
priority[key]有什么问题? -
@enzo “元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引“IPriority”类型。没有带有“字符串”类型参数的索引签名在类型 'IPriority' 上找到。"
-
@StupidMan that error does not occur with your example code 所以你应该写
priority[key]或更改问题以包含一个真正的minimal reproducible example。 -
@StupidMan 你有“元素隐式有一个'任何'类型......”错误,因为你可能没有将键定义为
const键。见this -
@StupidMan 您的 const 键必须是字符串,而不是数字或未定义。这是编译器所必需的。