带有传播成员的 TypeScript 接口(interface)

标签 typescript redux react-redux

我正在批量导入一堆属性

从 './billingUtil2' 导入 * 作为 actionCreators;

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

interface componentState {
    ...actionCreators
}

我的用例是,我想创建一个 React 组件并准确描述将从 Redux 接收的 Prop 的形状。所以理想情况下是沿着这些方向的东西

import * as actionCreators from './billingUtil2';

interface State {
    name: string;
    age: number
}

interface componentState extends State {
    ...actionCreators
}

然后我可以告诉 TypeScript 期待 componentState 形式的 Prop 。 我的 redux reducer 已经在返回实现接口(interface)的结果;我在这里的主要目标是避免手动输入每个 Action 创建者。

最佳答案

你可以创建一个 Intersection Type

import * as actionCreators from './billingUtil2';

type MyState = typeof actionCreators & {
    name: string
    age: number
}

或者从上面第二部分的代码中,您可以使用 State 接口(interface),

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

}

关于带有传播成员的 TypeScript 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43621934/

相关文章:

javascript - 从 React 中的按键捕获键码

Typescript - 如何添加扩展方法

typescript - 键入函数调用图

javascript - 如何将 TypeScript 项目编译为单个 JS 文件,以便可以在浏览器中使用

reactjs - redux 操作类型具有可选的有效负载属性-typescript 在 reducer 内提示

reactjs - 如果 2 个不同的 Prop 更改具有相同的值,则不会调用 componentWillReceiveProps

javascript - 在使用 redux 使用react时,业务逻辑应该去哪里(action creators 或 reducers)?

typescript - 检查函数参数是否是 typescript 中特定类型的枚举

redux - Flutter redux 如何进行轮询

javascript - 我可以在 React 和 Redux 中发送 AJAX 调用,而无需使用操作创建器和缩减器吗?