打字稿匿名类类型-HOC



我正在尝试创建一个通用的HOC,但是我在类型上遇到了一些麻烦

让我们开始简单:

class Abc extends React.Component<{}> {
    hello() {
    }
    render() {
        return <View />
    }
}

参考JSX,没有问题

<Abc
    ref={(r: Abc) => {
        r.hello();
    }}
/>

现在让我们创建一个匿名,就像HOC会返回

一样
const Bcd = class extends React.Component<{}> {
    hello() {
    }
    render() {
        return <View />
    }
}; 

做我们过去所做的同样的事情

<Bcd
    ref={(r: Bcd) => {
        r.load()
    }}
/>;

现在我们获得了TS2304: Cannot find name Bcd,对于以下(r: Bcd)

我试图将其更改为(r: (typeof Bcd)),但随后会抱怨typeof BcdBcd

不兼容

我是在做错什么还是打字的键法不支持?

在您的示例中, Abc是javaScript变量名称 tyspercript类型名称,而 Bcd是javaScript变量名称打字稿类型名称。Bcd的类型是{hello(): void} & React.Component<{}>的未命名的交点。因为该类型没有名称,您不能将其引用为打字稿代码中其他位置的类型。

最新更新