带有传播成员的 TypeScript 接口

TypeScript interface with spread members

我正在使用

批量导入一堆属性

import * as actionCreators from './billingUtil2';

并且 TypeScript 正确识别了 actionCreators 中的每个导出。是否可以将这些成员 "spread" 放入接口中?理想情况下是这样的,但有效

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

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

}