reactjs - typescript 指向函数

标签 reactjs typescript redux

我正在使用 TypeScript 和 redux 编写一个 ReactJS 应用程序。为了描述组件 props,我使用接口(interface)而不是 propTypes。这允许我在编译时检查 prop 类型。

一些 props 是函数(redux Action 创建者,由 connectdispatch 封装)。

如何用 TypeScript 表示我的组件属性属于该操作创建者函数签名?我的意思是我不想重复描述类型。

要了解更多问题,请查看下面的示例:

// here is my action creator
function someAction(prop1: number, prop2: string) {
  ...
}

interface IComponentProps {
  // here I want to say
  // that this is the same function as above,
  // but I have to duplicate its type signature
  someAction(prop1: number, prop2: string);
}

当然,我可以为该函数创建一个接口(interface):

interface ISomeActionFunction {
  (prop1: number, prop2: string): void
}

然后在函数声明和属性接口(interface)中都使用它,但我想知道是否有什么方法可以直接指向特定的函数?

最佳答案

正如您已经意识到的,使用界面是最好的方法。你可以让它看起来像这样:

interface IComponentProps {
    someAction: ISomeActionFunction;
}

interface ISomeActionFunction {
    (prop1: number, prop2: string): void;
}

const someAction: ISomeActionFunction = (p1, p2) => {
    // the compiler will correctly infer the types of p1 and p2 for you
    ...
}

这样,函数类型就不会重复,编译器仍然可以检查所有内容。

如果您预见需要大量操作创建者,您可以添加如下通用助手:

interface IBinaryActionCreator<T1, T2, TResult> {
  (prop1: T1, prop2: T2): TResult;
}

type ISomeActionFunction = IBinaryActionCreator<number, string, void>;

但这可能有点过分了。

关于reactjs - typescript 指向函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34543362/

相关文章:

javascript - 为什么当我使用空购物车登录时,会出现 .map 错误?

javascript - Redux-form - 有没有办法知道哪些字段已更改? (更新和补丁)

redux - 使用 react、redux 和 redux-form 对字段进行内联编辑。我应该这样做吗?

reactjs - React-Leaflet React 组件作为标记

javascript - 如何在 react-google-charts 中绘制与主要刻度、刻度长度、位置、颜色等刻度相关的样式

Javascript 返回函数发生得太晚了

typescript - 为什么长度应该是索引器的子类型?

javascript - variableName[0] 有更好的写法吗?

javascript - 通过自定义 Grunt 任务处理文件

javascript - 尝试在 React/Redux/Jest 中测试调度操作函数时获取未定义的 .then