带有传播成员的TypeScript接口

Ada*_*kis 4 typescript redux react-redux

我正在批量导入一堆属性

import * as actionCreators from './billingUtil2';

和TypeScript正确识别其中的每个导出actionCreators.是否有可能将这些成员"传播"到界面中?理想情况下这样,但有效

interface componentState {
    ...actionCreators
}
Run Code Online (Sandbox Code Playgroud)

我的用例是,我想创建一个React组件并准确描述它将从Redux接收的道具的形状.理想情况下沿着这些方向发展

import * as actionCreators from './billingUtil2';

interface State {
    name: string;
    age: number
}

interface componentState extends State {
    ...actionCreators
}
Run Code Online (Sandbox Code Playgroud)

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

wkr*_*ger 6

您可以创建交叉点类型

import * as actionCreators from './billingUtil2';

type MyState = typeof actionCreators & {
    name: string
    age: number
}
Run Code Online (Sandbox Code Playgroud)

或者从上面第二部分的代码中State,您可以使用界面

import * as actionCreators from './billingUtil2';

interface State {
    name: string;
    age: number
}

type componentShape = typeof actionCreators & State;
Run Code Online (Sandbox Code Playgroud)

或者你也可以这样做

type acT = typeof actionCreators
interface MyState extends acT {
    name; age;
}

class Comp extends React.Component<{}, MyState> {

}
Run Code Online (Sandbox Code Playgroud)