我正在尝试使用 TypeScript 创建一个 asyncComponent
高阶组件,但无法完全正确地获取类型。
本质上,这在 JS 中与 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.
有什么想法吗?
最佳答案
我会尽力解释在最新版本的 typescript 中出了什么问题以及如何解决的。
原因:
行为改变的原因是在 2.3 中,类似于包含新鲜度标志的对象字面量表达式,JSXAttributes 也是类型检查(这意味着不允许多余的属性)
建议的解决方案: - 请引用引用链接
- 只包含明确的属性 -> 不允许多余的属性
- 包含传播属性(即使有显式属性)-> 1。 检查类型可分配性(允许访问属性) 2. 对于每个 显式属性检查属性名称是否与目标匹配 姓名。
这个问题显然在 2.3.3 最新稳定版和 2.4.0 开发版中得到了解决。
使用 npm install typescript@next
为 nightly build
2.4.0 dev
或将 typescript 版本更新到最新的稳定版(2.3 .3)
关于reactjs - react 和 typescript 与 webpack 打字问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43684686/