Typescript 我们可以从字符串和数字组成对象键类型吗

问题描述 投票:0回答:1

我有以下界面:

interface AdvancedFilterState {
  customAttributesName1?: manualInputType,
  customAttributesValue1?: manualInputType,
  customAttributesName2?: manualInputType,
  customAttributesValue2?: manualInputType,

  ...and this can go forever
}

我想要一个匹配

customAttributesName
和一个数字以及
customAttributesValue
和一个数字的关键模式。

为了获得此通行证,我使用了一种像这样的通用模式的方法

interface AdvancedFilterState {
  [key: string]: someType
}

我可以做类似的事情吗

type keytype = 'customAttributesName' + number;
interface AdvancedFilterState {
  [key: keytype]: someType
}

如何在打字稿中解决这个问题?

typescript
1个回答
0
投票

以下是实现此目标的方法:

interface AdvancedFilterState {
  [key: `customAttributesName${number}` | `customAttributesValue${number}`]: number
}

让我们测试一下:

const test: AdvancedFilterState = {
  customAttributesName1: 'asdad',
  customAttributesName4: 'ad',
  customAttributesNamea: 'ad', // Error
}
© www.soinside.com 2019 - 2024. All rights reserved.