簡體   English   中英

使用webpack輸入問題進行反應和打字

[英]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也是類型檢查(這意味着不允許多余的屬性)

建議的解決方案: - 參考參考鏈接

  1. 僅包含顯式屬性 - >不允許多余屬性
  2. 包含擴展屬性(即使使用顯式屬性) - > 1.檢查類型可分配性(允許訪問屬性)2。對於每個顯式屬性,檢查屬性名稱是否與目標名稱匹配。

這個問題在2.3.3最新穩定版本和2.4.0開發中顯然已得到解決。

使用npm install typescript@next進行2.4.0 devnightly build或將typescript版本更新到最新的stable(2.3.3)

參考: Issuse Tracker

您的示例在TypeScript最新版中編譯正常且沒有錯誤:

在此輸入圖像描述

更多

  • 更新到typescript@next

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM