因此我们可以解决一个问题,即我们有一个提供创建样式方法的接口(interface)。它接受泛型并将返回类型参数化,如下所示:
export interface StyleConfig {
rootContainer: any;
}
export default interface AcceptsStyles {
createStyles: <C extends StyleConfig>(theme: any) => C;
}
现在在使用这个接口(interface)的类中,我们试图传递我们想要的接口(interface) C
成为:
export const defaultProps: Partial<Props<any>> = {
createStyles: function <ListItemStyleConfig>(theme: any): ListItemStyleConfig { return Styles(theme) },
};
我们已经设法使用正常的函数定义让它工作;然而,如果我们用箭头函数来尝试它,它会给我们带来问题:
createStyles<ListItemStyleConfig>: (theme: any): ListItemStyleConfig => Styles(theme),
我不确定我们是否只是以正确的方式或其他方式对其进行参数化,但我们会收到类似 Type '<ListItemStyleConfig>() => (theme: any) => any' is not assignable to type '<C extends StyleConfig>(theme: any) => C'.
Type '(theme: any) => any' is not assignable to type 'C'.
的错误
有没有人知道我们如何在本质上使用箭头函数来完成我们在正常函数定义中所做的事情,这是否是正确的方法?
最佳答案
您可能不需要 <ListItemStyleConfig>
在你的 createStyles
, TS 编译器几乎总是能够从函数的返回值中推断出泛型类型。
createStyles: (theme: any): ListItemStyleConfig => Styles(theme) // As long as Props extends AcceptsStyles, the function will be correctly inferred and valid
取决于 Styles
的返回类型,您甚至可能不需要返回类型(并且可以推断),例如
createStyles: (theme: any) => Styles(theme) // should infer the generic from return type of Styles
或者,根据 Styles 的签名(以及它是否使用无限制的 this
),您甚至可以像这样直接传递它:
createStyles: Styles // equivalent to theme => Styles(theme) as long as binding is the same and Styles takes only a single parameter
TypeScript 编译器几乎总能为您推断出泛型!除非有歧义,否则我尽量避免明确声明它们。
关于javascript - 在 React 中使用泛型键入 defaultProp 箭头函数方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54556788/