[英]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: {...}
}
}
OR或者
{
allIds: ['1'],
byId: {
'1': {...}
}
}
I'm trying to create an interface called IOutput
to cater for this.我正在尝试创建一个名为
IOutput
的接口来满足此需求。
I've tried this:我试过这个:
interface IOutput {
allIds: string[] | number[]
byId: {
[key: number | string]: any
}
}
But it gives me the following error但它给了我以下错误
An index signature parameter type must be 'string' or 'number'.
索引签名参数类型必须是“字符串”或“数字”。 ts(1023)
ts(1023)
It seems to work when I do this:当我这样做时,它似乎有效:
interface IOutput {
allIds: string[] | number[]
byId: {
[key: number]: any
}
}
OR或者
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?我怎样才能完成我想做的事情?
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).索引签名参数只能是
number
或string
(正是这些类型,不是它们的联合,不是文字类型)。 You can however have two index signatures, one for number
and one for string
.但是,您可以有两个索引签名,一个用于
number
,一个用于string
。
There is another small quick, if you have a string
signature, you can actually index by number
as well.还有一个小技巧,如果你有一个
string
签名,你实际上也可以按number
索引。 So this means that if the string
index and the number
index have the same return type you just need the string index所以这意味着如果
string
索引和number
索引具有相同的返回类型,您只需要字符串索引
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': {}
}
}
Now the limitation to write indexes has been removed.
现在删除了写入索引的限制。 An index signature parameter can be union of
number
andstring
.索引签名参数可以是
number
和string
的并集。
type StringMap = { [key: string | number]: unknown };
function createStringPair(property: keyof StringMap, value: number): StringMap {
return { [property]: value };
}
console.log(createStringPair(5, 10));
console.log(createStringPair("sum", 10));
[LOG]: {
"5": 10
}
[LOG]: {
"sum": 10
}
Cheers, hope it helps.干杯,希望它有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.