我要动态Array<string>
然后产生动态 Object
与 key
/property
从数组的值。 (用于 reactjs typescript 中的 Prop 用法)
这是一个示例代码:
interface Props {
buttons: Array<string>;
buttonProps?: { [key: string]: string }; //want key here to correspond with values of buttons
}
我猜你在这里使用泛型,但我不确定如何继续。
最佳答案
因为 key 是 string
你必须添加一个泛型,否则任何字符串都是有效的,这意味着你可以在按钮和 buttonProps 中放置任何东西。
我希望我正确回答了这个问题。
interface Props<T extends keyof any = keyof any> {
buttons: Array<T>;
buttonProps?: { [key in T]: string };
};
const buttons: Props<'test1' | 'test2'> = {
buttons: [
'test1', 'test2',
],
buttonProps: {
test1: 'string1',
test2: 'string2',
},
};
关于arrays - 使用随机数组字符串键入对象键/属性 - TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61894473/