我正在使用Typescript为我的React项目编写一个高阶组件,这基本上是一个函数,它接受React组件作为参数并返回一个环绕它的新组件。
然而,正如预期的那样,TS抱怨“导出函数的返回类型具有或正在使用私有名称” Anonymous class”。
有问题的功能:
export default function wrapperFunc <Props, State> ( WrappedComponent: typeof React.Component, ) { return class extends React.Component<Props & State, {}> { public render() { return <WrappedComponent {...this.props} {...this.state} />; } }; }
该错误是合理的,因为未导出包装器函数的返回类,而其他模块导入则该函数无法知道返回值是什么。但是我无法在此函数外部声明返回类,因为它需要将组件传递包装到外部函数。
typeof React.Component像下面这样显式指定返回类型的试验确实可以消除此错误。
typeof React.Component
有问题的函数具有显式返回类型:
export default function wrapperFunc <Props, State> ( WrappedComponent: typeof React.Component, ): typeof React.Component { // <== Added this return class extends React.Component<Props & State, {}> { public render() { return <WrappedComponent {...this.props} {...this.state} />; } }; }
但是,我不确定这种方法是否有效。它是解决TypeScript中特定错误的正确方法吗?(或者我是否在其他地方产生了意外的副作用?或者有其他更好的方法?)
(编辑)根据丹尼尔的建议更改引用的代码。
使用TypeScript的React高阶组件的类型注释
返回类型typeof React.Component是真实的,但对于包装组件的用户不是很有用。它丢弃有关组件接受什么道具的信息。
为此,React类型提供了一个方便的类型React.ComponentClass。它是类的类型,而不是从该类创建的组件的类型:
React.ComponentClass
React.ComponentClass<Props>
(请注意,该state类型是内部细节,因此未提及)。
state
在您的情况下:
export default function wrapperFunc <Props, State, CompState> ( WrappedComponent: typeof React.Component, ): React.ComponentClass<Props & State> { return class extends React.Component<Props & State, CompState> { public render() { return <WrappedComponent {...this.props} {...this.state} />; } }; }
但是,您在使用WrappedComponent参数做相同的事情。根据您在内部使用它的方式render,我猜测还应该声明它:
WrappedComponent
render
WrappedComponent: React.ComponentClass<Props & State>,
但这是一个大胆的猜测,因为我认为这不是完整的功能(CompState未使用,并且Props & State可能是单个类型参数,因为它始终以该组合形式出现)。
CompState
Props & State