我很难创建一个表示组件状态的接口。 假设以下内容:
interface IFoo {
fooName: string;
fooValue: string | boolean | Array<string>
}
然后我们有以下对象:
const objOne: IFoo = {
fooName: 'objOneName',
fooValue: true
}
const objTwo: IFoo = {
fooName: 'objTwoName',
fooValue: ['a', 'b', 'c']
}
现在我们有了一个包含那些对象的数组:
const myArray: IFoo[] = [objOne, objTwo];
现在在React组件中,我将myArray用作道具,并且需要构造组件状态的接口。
我需要一个新的接口来表示React组件的状态,它看起来应如下所示:
interface myState {
someProp: string;
// The following values need to be dynamic. I don't know how many entries are there in the array
// in the is example: objOneName is the value of objOne[fooName] and it's type is the type of obj[fooValue]
objOneName: boolean,
objTwoName: Array<string>
}
答案 0 :(得分:1)
您可以创建以下通用道具
interface ArbitraryProps {
[key: string]: string | boolean | Array<string>
}
interface myState extends ArbitraryProps {
someProp: string;
}
我提取了ArbitraryProps
作为单独的界面,因为我想您想对通过它发送组件的props进行类型检查。另外,这种方法可能太宽松了,但是感觉就像我们只能通过重新考虑此处的设计才能发挥作用...