我正在使用 TypeScript 和 redux 编写一个 ReactJS 应用程序。为了描述组件 props,我使用接口(interface)而不是 propTypes。这允许我在编译时检查 prop 类型。
一些 props 是函数(redux Action 创建者,由 connect
和 dispatch
封装)。
如何用 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/