出奇,${string}${number}
只是意味着“单个字符后跟一个数字”即使${string}
其本身(后面没有另一个占位符)将允许多个字符。有一个功能建议 https://github.com/microsoft/TypeScript/issues/42903...更新...该行为(最初是错误报告),但它被语言创建者标记为“按预期工作”并关闭。
直到/除非他们这样做,你可以定义SlotName
作为一组模式的联合以允许多个字符:
type SlotName =
`${string}${number}Slot` |
`${string}${string}${number}Slot` |
`${string}${string}${string}${number}Slot` |
`${string}${string}${string}${string}${number}Slot` |
`${string}${string}${string}${string}${string}${number}Slot` |
`${string}${string}${string}${string}${string}${string}${number}Slot` |
`${string}${string}${string}${string}${string}${string}${string}${number}Slot` |
`${string}${string}${string}${string}${string}${string}${string}${string}${number}Slot`;
这允许:
const x: TheInterface = {
c3Slot: {type: "a"},
cu3Slot: {type: "b"},
cxx3Slot: {type: "c"},
cxxx3Slot: {type: "d"},
cxxxx3Slot: {type: "e"},
cxxxxx3Slot: {type: "f"},
cxxxxxx3Slot: {type: "g"},
cxxxxxxx3Slot: {type: "h"},
};
不理想,但它有效。继续根据需要选择尽可能多的角色。
(也许比我更擅长 TypeScript 的人可以指出如何使用递归或映射类型。)