【发布时间】:2018-10-10 13:30:03
【问题描述】:
我有如下 TypeScript 代码:
interface Props<T> {}
function HOC<P>(component: React.ComponentType<P>): React.ComponentType<P> {
return component;
}
const MyClass = HOC(class MyClass<T> extends React.Component<Props<T>, {}> {});
type MyClass<T> = React.ComponentType<Props<T>>;
function render() {
return <MyClass<string> />;
}
但这不起作用,因为我在MyClass<string> 一行收到以下错误:
[ts]
JSX element type 'ReactElement<any> | null' is not a constructor function for JSX elements.
Type 'null' is not assignable to type 'ElementClass'.
[ts] Expected 0 type arguments, but got 1.
如果我删除 HOC 和类型声明,它编译得很好:
interface Props<T> {}
class MyClass<T> extends React.Component<Props<T>, {}> {};
function render() {
return <MyClass<string> />;
}
所以我的问题是,假设我无法修改HOC 的类型声明,我该如何声明const MyClass(必要时使用type MyClass<T>)以便第一个示例编译成功?
【问题讨论】:
-
如果您不喜欢编写可能会随着代码更改和隐藏问题而过时的类型断言,请参阅this answer 了解另一种方法。
标签: reactjs typescript jsx