Typescript `typeof React.Component` 不扩展接口?无法定义高阶组件

Typescript `typeof React.Component` does not extend interface? Trouble defining higher-order component

我正在创建一个高阶组件来包装一个扩展接口的组件:

interface ClickOutsideInterface {
  onClickOutside: (e: Event) => void
}

我创建的工厂需要 React.ComponentClass 实现 ClickOutsideInterface:

  function clickOutside<P>(Component: React.ComponentClass<P> & ClickOutsideInterface){    
    return class ClickOutside extends React.Component<P, {}> { 
      /* on click outside invoke Component.onClickOutside  */

      render() {
        return(<div><Component {...this.props} /></div>)
      }
   }
}

为了测试工厂,我实现了一个扩展 ClickOutsideInterface

的组件
class Test extends React.Component<TProps, TState> implements ClickOutsideInterface {
  onClickOutside(event: Event): void {
    this.setState({
      closed: true
    })
  }

  render(){
    return(
      <div>{this.state.closed}</div>
    )
  }
}

但是当我将组件用作函数中的参数时 clickOutside:

const withClickOutside = clickOutside(Test)

我收到参数 Test 的以下类型错误:

Argument of type 'typeof Test' is not assignable to parameter of type 'ComponentClass & ClickOutsideInterface'. Type 'typeof Test' is not assignable to type 'ClickOutsideInterface'. Property 'onClickOutside' is missing in type 'typeof Test'.

知道为什么 Typescript 认为我没有在 Test 中实现接口吗?

TypeScript 说你还没有实现你的函数需要它的参数的接口,因为你确实没有。

写的时候

class A {
  //...
}

您定义了两种类型和一种值。

名为 A 是 class。它是您使用 new 调用以创建对象的函数。

第一个 type,也被命名为 A,是通过调用创建的对象的类型class 函数与 new 如上所述。

第二个 type 是那个 class 函数的类型。声明 class 不会自动为此类型创建名称,但类型存在 none 越少,因为所有值都有一个类型。这个类型写成typeof A是因为它是值A的类型,class.

的类型

因此,根据您要完成的目标,您需要

传递 Test

的实例
const withClickOutside = clickOutside(new Test);

或者更改您的函数,使其接收与 class 自身类型匹配的对象,而不是它创建的对象

function clickOutside<P>(
  Component: new () => React.ComponentClass<P> & ClickOutsideInterface
) {...}

我怀疑在这种情况下你想要的是后者。

最后,虽然您可能希望它用于完全有效的文档目的,但我想指出,没有理由实际声明您的 class 甚至根本实现了该接口。 TypeScript 是一种结构类型语言,所有接口都通过具有兼容成员来实现。