我尝试使用TypeScript创建一个asyncComponent
高阶组件,但无法正确获取类型。
基本上,这适用于JS with webpack ...
const Auth = asyncComponent(() =>
require.ensure([], require => require("../auth/index").default, "auth_async"),
);
我的asyncComponent
是一个更高阶函数,执行以下操作...
import * as React from "react";
import { Component } from 'react';
export interface IAsyncComponentProps {}
export interface IAsyncComponentState {
Component: typeof Component
}
interface IGetComponent {
(): Promise<typeof Component>;
}
export default function asyncComponent (getComponent: IGetComponent) {
let ComponentCache: typeof Component = null;
return class AsyncComponent extends Component<IAsyncComponentProps, IAsyncComponentState> {
state: {
Component: typeof Component,
};
constructor(props: IAsyncComponentProps) {
super(props);
this.state = { Component: ComponentCache };
}
componentWillMount() {
if (!this.state.Component) {
getComponent().then((Component) => {
ComponentCache = Component;
this.setState({ Component });
});
}
}
render() {
const { Component } = this.state;
if (Component) {
return <Component {...this.props} />;
}
return null;
}
};
}
但是,我在编译时遇到错误......
src/components/asyncComponent/index.tsx(40,27): error TS2322: Type '{ children?: ReactNode; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<P, S>> & Readonly<{ children?: ReactNode...'.
Type '{ children?: ReactNode; }' is not assignable to type 'Readonly<P>'.
src/index.ts(3,7): error TS1141: String literal expected.
11:06:50 AM - Compilation complete. Watching for file changes.
有什么想法吗?
答案 0 :(得分:3)
我会尽力解释在最新版本的打字稿中出了什么问题以及如何解决。
<强>原因:强>
行为改变的原因是在2.3中,类似于包含新鲜度标志的对象文字表达式,JSXAttributes也是类型检查(这意味着不允许多余的属性)
建议的解决方案: - 请参阅参考链接
这个问题在2.3.3最新稳定版和2.4.0开发版中显然已得到解决。
将npm install typescript@next
用于nightly build
2.4.0 dev
或将打字稿版本更新为最新版本(2.3.3)
答案 1 :(得分:2)