TypeScript:尝试使用 string | 时,索引签名参数必须是“字符串"或“数字"数字 [英] TypeScript: An index signature parameter must be a 'string' or 'number' when trying to use string | number
问题描述
我正在尝试创建一个函数来规范化我的数组,它需要一个结构如下的输出对象:
I'm attempting to create a function to normalize my arrays and it's expecting an output object that is structured like this:
{
allIds: [1],
byId: {
1: {...}
}
}
或
{
allIds: ['1'],
byId: {
'1': {...}
}
}
我正在尝试创建一个名为 IOutput
的接口来满足此需求.
I'm trying to create an interface called IOutput
to cater for this.
我已经试过了:
interface IOutput {
allIds: string[] | number[]
byId: {
[key: number | string]: any
}
}
但它给了我以下错误
索引签名参数类型必须是字符串"或数字".ts(1023)
An index signature parameter type must be 'string' or 'number'. ts(1023)
当我这样做时它似乎有效:
It seems to work when I do this:
interface IOutput {
allIds: string[] | number[]
byId: {
[key: number]: any
}
}
或
interface IOutput {
allIds: string[] | number[]
byId: {
[key: string]: any
}
}
但这不是我想要完成的.我也试过这个,它给了我同样的错误:
But that's not what I'm trying to accomplish. I've also tried this and it gives me the same error:
type StringOrNumber = string | number
interface IOutput {
allIds: string[] | number[]
byId: {
[key: StringOrNumber ]: any
}
}
我怎样才能完成我想做的事?
How can I accomplish what I'm trying to do?
推荐答案
这是我们当前编写索引方式的一个限制(这将改变 很快).索引签名参数只能是 number
或 string
(正是这些类型,不是它们的联合,也不是文字类型).但是,您可以有两个索引签名,一个用于 number
,另一个用于 string
.
This is a limitation of the current way we can write indexes (this will change soon enough). An index signature parameter can only be number
or string
(exactly those types, not a union of them, not literal types). You can however have two index signatures, one for number
and one for string
.
还有一个小问题,如果你有一个 string
签名,你实际上也可以按 number
索引.所以这意味着如果 string
索引和 number
索引具有相同的返回类型,您只需要字符串索引
There is another small quick, if you have a string
signature, you can actually index by number
as well. So this means that if the string
index and the number
index have the same return type you just need the string index
interface IOutput {
allIds: string[] | number[]
byId: {
[key: string]: any
// [key: number]: any // Valid but not necessary
}
}
let o: IOutput = {
allIds: [1],
byId: {
1: {}
}
}
let o2: IOutput = {
allIds: ['1'],
byId: {
'1': {}
}
}
这篇关于TypeScript:尝试使用 string | 时,索引签名参数必须是“字符串"或“数字"数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!