【问题标题】:TypeScript interface with spread members带有扩展成员的 TypeScript 接口
【发布时间】:2017-09-23 03:11:11
【问题描述】:

我正在批量导入一堆属性

import * as actionCreators from './billingUtil2';

TypeScript 可以正确识别 actionCreators 内的每个导出。是否可以将这些成员“传播”到界面中?理想情况下是这样的,但有效

interface componentState {
    ...actionCreators
}

我的用例是,我想创建一个 React 组件并准确地描述它将从 Redux 接收到的道具的形状。所以理想情况下是这样的

import * as actionCreators from './billingUtil2';

interface State {
    name: string;
    age: number
}

interface componentState extends State {
    ...actionCreators
}

然后我可以告诉 TypeScript 期待 componentState 形式的道具。 我的 redux reducer 已经返回了实现接口的结果;我的主要目标是避免手动输入每个动作创建者。

【问题讨论】:

    标签: typescript redux react-redux


    【解决方案1】:

    你可以创建一个Intersection Type

    import * as actionCreators from './billingUtil2';
    
    type MyState = typeof actionCreators & {
        name: string
        age: number
    }
    

    或者从上面第二部分的代码中,你有State 接口,你可以这样做

    import * as actionCreators from './billingUtil2';
    
    interface State {
        name: string;
        age: number
    }
    
    type componentShape = typeof actionCreators & State;
    

    或者你也可以这样做

    type acT = typeof actionCreators
    interface MyState extends acT {
        name; age;
    }
    
    class Comp extends React.Component<{}, MyState> {
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-04
      • 2020-10-30
      • 2020-06-09
      • 2016-07-06
      • 2017-10-21
      • 2020-04-09
      • 2018-06-20
      • 2018-04-09
      相关资源
      最近更新 更多