带有传播成员的TypeScript接口

时间:2017-04-25 22:19:57

标签: typescript redux react-redux

我用

批量导入一堆属性

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已经在返回实现接口的结果;我的主要目标是避免手动输入每个动作创建者。

1 个答案:

答案 0 :(得分:5)

您可以创建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> {

}