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

shu*_*ksh 7 typescript reactjs

我正在使用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} />;
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

错误是合理的,因为没有导出返回的包装函数类,而其他模块导入此函数无法知道返回值是什么.但我无法在此函数之外声明返回类,因为它需要将组件传递包装到外部函数.

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} />;
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

但是,我不确定这种方法的有效性.它是否被认为是解决TypeScript中此特定错误的正确方法?(或者我是否在其他地方造成了意想不到的副作用?或者更好的方法是这样做?)

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

Dan*_*ker 5

使用TypeScript的React高阶组件的类型注释

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

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

React.ComponentClass<Props>
Run Code Online (Sandbox Code Playgroud)

(请注意,该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} />;
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

但是,您在使用WrappedComponent参数做相同的事情。根据您在内部的使用方式render,我猜测还应该声明它:

WrappedComponent: React.ComponentClass<Props & State>,
Run Code Online (Sandbox Code Playgroud)

但这是一个疯狂的猜测,因为我认为这不是完整的功能(CompState未使用,并且Props & State可能是单个类型参数,因为它始终以该组合形式出现)。