我正在使用TypeScript和redux编写reactjs应用程序。要使用接口而不是now()
来描述组件道具。这允许我在编译时检查道具类型。
一些道具是函数(redux动作创建者,由propTypes
包裹connect
)。
如何说我的组件属性属于该动作创建者函数签名的TypeScript?我的意思是我不想重复描述类型。
要了解更多问题,请查看以下示例:
dispatch
当然,我可以为该功能创建一个界面:
// 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);
}
然后在函数声明和属性界面中使用它,但我想知道是否有任何方法可以直接指向特定的函数?
答案 0 :(得分:1)
正如您已经意识到的那样,使用界面是您最好的方法。你可以看起来像这样:
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>;
但这可能有点矫枉过正。