我正在尝试创建一个通用的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()
}}
/>;
现在我们为下面的(r: Bcd)
获取TS2304: Cannot find name Bcd
。
我尝试将其更改为(r: (typeof Bcd))
,但随后它会抱怨typeof Bcd
与Bcd
不兼容
我是不是做错了什么,或者typescript不支持这种类型的输入?
发布于 2019-03-20 04:21:36
在您的示例中,Abc
是JavaScript变量名和TypeScript类型名,而Bcd
是JavaScript变量名,但不是TypeScript类型名。Bcd
的类型是{hello(): void} & React.Component<{}>
的未命名intersection type。因为该类型没有名称,所以不能在TypeScript代码中将其作为类型引用。
https://stackoverflow.com/questions/55249067
复制相似问题