我有以下界面:
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
}
如何在打字稿中解决这个问题?
以下是实现此目标的方法:
interface AdvancedFilterState {
[key: `customAttributesName${number}` | `customAttributesValue${number}`]: number
}
让我们测试一下:
const test: AdvancedFilterState = {
customAttributesName1: 'asdad',
customAttributesName4: 'ad',
customAttributesNamea: 'ad', // Error
}