【发布时间】:2022-01-05 08:19:28
【问题描述】:
我正在尝试将接口声明中的键设为通用,这样如果我向接口传递一个字符串,则键将是一个字符串。
K 出错:An index signature parameter type must be either 'string' or 'number'。
interface SomeObj<K , V> {
bar: {
[P in K]: V
}
};
const foo: SomeObj<string, number> = {
bar: {hello: 1234}
}
【问题讨论】:
-
你想要一个映射类型而不是索引签名......它看起来像
{[P in K]: V}而不是{[k: K]: V}。这相当于Record<K, V>。有关更多信息,请参阅链接问题的 answer。 -
这也行不通,因为
P in K会将 K 视为字符串值的联合。我正在寻找k的类型而不是值。像 [k: string]: V]这样的东西会起作用,但如果我替换string withK`。它不会快乐。 -
好吧,我重新打开了这个问题,但我不明白
Record<K, V>怎么不适合你。你说“行不通”……你试过了吗? -
确保将错误更新为“
Type 'K' is not assignable to type 'string | number | symbol'”而不是“An index signature parameter type must be either 'string' or 'number'”。
标签: typescript typescript-typings typescript-generics