【问题标题】:Construct a generic interface with typescript用 typescript 构造一个通用接口
【发布时间】:2020-04-10 16:21:54
【问题描述】:

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

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

【问题讨论】:

    标签: reactjs typescript typescript-typings typescript-generics


    【解决方案1】:

    您可以创建以下通用道具

    interface ArbitraryProps {
        [key: string]: string | boolean | Array<string>
    }
    
    interface myState extends ArbitraryProps { 
        someProp: string;
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      • 2012-12-01
      • 1970-01-01
      • 2020-06-09
      • 2018-03-21
      相关资源
      最近更新 更多