TypeScript 中受控的 prop 名称

2024-03-31

我遇到了 TypeScript 打字问题,找不到任何相关内容。

我正在尝试向我的组件添加动态插槽,并希望 props 的名称是一个特定的模板,包括任何字符串、数字和“Slot”字符串(即 custom3Slot)。

我想要实现的是在我的组件的 props TS 声明中声明这种类型的 props:

[key: SlotName]: ReactElement; 

目前,SlotName 的声明如下:

type SlotName = `${string}${number}Slot`;

问题是第一个字符串只能包含一个字符。因此“c3Slot”有效,但“cu3Slot”或“custom3Slot”无效。我找不到一种方法使第一个字符串具有任意长度。

完整示例():

type SlotName = `${string}${number}Slot`;

interface TheInterface {
    [key: SlotName]: ReactElement; 
}

const x: TheInterface = {
    c3Slot:  /*...*/,
    cu3Slot: /*...*/, // Error: Object literal may only specify known
                      // properties, and 'cu3Slot' does not exist in type
                      // 'TheInterface'. (2322)
};

出奇,${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 的人可以指出如何使用递归或映射类型。)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TypeScript 中受控的 prop 名称 的相关文章

随机推荐