TypeScript:尝试使用字符串|时,索引签名参数必须为“字符串"或“数字"数字 [英] TypeScript: An index signature parameter must be a 'string' or 'number' when trying to use string | number

查看:316
本文介绍了TypeScript:尝试使用字符串|时,索引签名参数必须为“字符串"或“数字"数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数来规范化我的数组,并且期望一个结构如下的输出对象:

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': {...}
  }
}

我正在尝试创建一个名为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
  }
}

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). 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:尝试使用字符串|时,索引签名参数必须为“字符串"或“数字"数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆