[英]React and typescript with webpack typing issue
我正在嘗試使用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.
有任何想法嗎?
我將盡力解釋最新版本的打字稿中出了什么問題以及如何解決。
原因:
行為改變的原因是在2.3中,類似於包含新鮮度標志的對象文字表達式,JSXAttributes也是類型檢查(這意味着不允許多余的屬性)
建議的解決方案: - 參考參考鏈接
這個問題在2.3.3最新穩定版本和2.4.0開發中顯然已得到解決。
使用npm install typescript@next
進行2.4.0 dev
的nightly build
或將typescript版本更新到最新的stable(2.3.3)
參考: Issuse Tracker
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.