reactjs - react 和 typescript 与 webpack 打字问题

标签 reactjs typescript webpack

我正在尝试使用 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. 包含传播属性(即使有显式属性)-> 1。 检查类型可分配性(允许访问属性) 2. 对于每个 显式属性检查属性名称是否与目标匹配 姓名。

这个问题显然在 2.3.3 最新稳定版和 2.4.0 开发版中得到了解决。

使用 npm install typescript@nextnightly build 2.4.0 dev 或将 typescript 版本更新到最新的稳定版(2.3 .3)

引用:Issuse Tracker

关于reactjs - react 和 typescript 与 webpack 打字问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43684686/

相关文章:

django - 使用 Flask/Django 和 javascript 前端进行身份验证

javascript - useState 中的变量未在 useEffect 回调中更新

javascript - 在 React (v0.14.8) 中加载 Meteor (v1.3) 数据的首选方式

reactjs - react 路由器错误 : Cannot read properties of undefined (reading 'pathname' )

javascript - 即使我已经传递了另一个引用,数组仍然以某种方式遵循引用

css - Webpack:如何在css sourcemap中获取相对路径

node.js - 将winston 更新到版本3.2.1 后出错。 TypeError : self. _addDefaultMeta 不是函数

javascript - 检查对象中是否只有一个数组有值

javascript - fat-arrow 函数返回的剩余运算符

javascript - 带有 ReactJS 的 ASP.NET 6 - 使用 react-scripts 5.0.0 热重载时浏览器不刷新