ค้นหาเว็บไซต์

reactjs - React และ typescript กับปัญหาการพิมพ์ของ webpack


ฉันกำลังพยายามสร้าง asyncComponent higher order component ด้วย TypeScript แต่ยังไม่สามารถทำให้ประเภทถูกต้องได้

โดยพื้นฐานแล้ว สิ่งนี้ทำงานใน 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.

มีไอเดียอะไรไหม?

คำตอบ #1

ฉันจะพยายามอย่างดีที่สุดที่จะอธิบายว่าเกิดอะไรผิดพลาดและมันได้รับการแก้ไขอย่างไรในรุ่นล่าสุดของ TypeScript

เหตุผล:

สาเหตุของการเปลี่ยนแปลงพฤติกรรมคือว่าในเวอร์ชัน 2.3 คล้ายกับนิพจน์อ็อบเจ็กต์ลิทเทอรัลที่มีแฟล็กความสดใหม่ JSXAttributes ก็ถูกตรวจสอบชนิดเช่นกัน (ซึ่งหมายความว่าคุณสมบัติเกินไม่ถูกอนุญาต)

ข้อเสนอแนะในการแก้ปัญหา: - อ้างอิงจากลิงก์อ้างอิง

  1. ต้องมีเพียงแอตทริบิวต์ที่ระบุไว้ชัดเจน -> ไม่อนุญาตคุณสมบัติเพิ่มเติม
  2. มีคุณสมบัติแบบกระจาย (แม้ว่าจะมีคุณสมบัติแบบชัดเจน) -> 1. ตรวจสอบความสามารถในการกำหนดประเภท (อนุญาตให้เข้าถึงคุณสมบัติ) 2. สำหรับคุณสมบัติแบบชัดเจนแต่ละรายการ ตรวจสอบว่าชื่อคุณสมบัติตรงกับชื่อเป้าหมายหรือไม่

ปัญหานี้ดูเหมือนว่ากำลังถูกแก้ไขในเวอร์ชันเสถียรล่าสุด 2.3.3 และในเวอร์ชันพัฒนา 2.4.0 ด้วย

ใช้ npm install typescript@next สำหรับ nightly build ที่เป็น 2.4.0 dev หรืออัปเดตเวอร์ชันของ TypeScript เป็นเวอร์ชันเสถียรล่าสุด (2.3.3)

อ้างอิง: ตัวติดตามปัญหา

คำตอบ #2

ตัวอย่างของคุณคอมไพล์ได้โดยไม่มีข้อผิดพลาดใน TypeScript เวอร์ชันล่าสุด:

เพิ่มเติม

  • อัปเดตเป็น typescript@next

บทความที่เกี่ยวข้อง