我正在使用TypeScript和redux编写一个reactjs应用程序。为了描述组件道具,我使用的是接口而不是propTypes
。这使我可以在编译时检查prop类型。
一些道具是函数(Redux的动作的创作者,通过包裹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 ISomeActionFunction {
(prop1: number, prop2: string): void
}
然后在函数声明和属性接口中都使用它,但是我想知道是否有任何方法可以直接指向特定函数?
正如您已经意识到的那样,使用界面是您的最佳方法。您可以使它看起来像这样:
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>;
但这可能太过分了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句