使用TypeScript为React高阶组件键入注释

问题描述 投票:5回答:2

我正在使用Typescript为我的React项目编写一个高阶组件,它基本上是一个函数接受一个React组件作为参数并返回一个包装它的新组件。

然而,由于它按预期工作,TS抱怨“返回类型的导出函数已经或正在使用私有名称”匿名类“。

有问题的功能:

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的试验可以抑制此错误。

有明确返回类型的函数:

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中此特定错误的正确方法? (或者我是否在其他地方造成了意想不到的副作用?或者更好的方法是这样做?)

(编辑)根据丹尼尔的建议更改引用的代码。

reactjs typescript
2个回答
4
投票

Type annotation for React Higher Order Component using TypeScript

返回类型typeof React.Component是真实的,但对包装组件的用户不是很有帮助。它会丢弃有关组件接受哪些道具的信息。

React打字为这个目的提供了一个方便的类型,React.ComponentClass。它是类的类型,而不是从该类创建的组件的类型:

React.ComponentClass<Props>

(请注意,未提及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: React.ComponentClass<Props & State>,

但这是一个疯狂的猜测,因为我认为这不是完整的函数(CompState没有使用,Props & State也可能是单一类型参数,因为它总是出现在该组合中)。


0
投票

输入参数的更合适的类型是React.ComponentType,因为它也处理无状态组件。

type ComponentType<P = {}> = ComponentClass<P> | StatelessComponent<P>

以下是澄清其用法的示例。

import * as React from 'react';

export default function <P = {}>(
  WrappedComponent: React.ComponentType<P>
): React.ComponentClass<P> {
  return class extends React.Component<P> {
    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
}  
© www.soinside.com 2019 - 2024. All rights reserved.