首页 > 解决方案 > 用 typescript 构造一个通用接口

问题描述

我很难创建一个代表组件状态的接口。假设如下:

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 作为道具,需要为组件状态构造接口。

我需要一个新的接口来表示反应组件的状态,它应该如下所示:

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>
}

标签: reactjstypescripttypescript-typingstypescript-generics

解决方案


您可以创建以下通用道具

interface ArbitraryProps {
    [key: string]: string | boolean | Array<string>
}

interface myState extends ArbitraryProps { 
    someProp: string;
}

我将其提取ArbitraryProps为一个单独的接口,因为我想您想对通过它发送组件的道具进行类型检查。此外,这种方法可能太松散了,但这感觉就像我们只能通过重新思考这里的设计来获得高度......


推荐阅读