【问题标题】:React and typescript with webpack typing issue反应和打字稿与 webpack 打字问题
【发布时间】:2017-09-26 20:05:06
【问题描述】:

我正在尝试使用 TypeScript 创建一个 asyncComponent 高阶组件,但不能完全正确地获取类型。

本质上,这适用于带有 webpack 的 JS...

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.

有什么想法吗?

【问题讨论】:

    标签: reactjs typescript webpack


    【解决方案1】:

    我会尽力解释最新版本的 typescript 中出了什么问题以及如何解决的。

    原因:

    行为改变的原因是在 2.3 中,类似于包含新鲜度标志的对象字面量表达式,JSXAttributes 也是类型检查(这意味着不允许多余的属性)

    建议的解决方案: - 参考参考链接

    1. 只包含明确的属性 -> 不允许有多余的属性
    2. 包含扩展属性(即使具有显式属性)-> 1。 检查类型可分配性(允许访问属性) 2. 对于每个 显式属性检查属性名称是否与目标匹配 名字。

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

    将nightly build 使用npm install typescript@next 即2.4.0 dev 或将打字稿版本更新为最新的稳定版(2.3.3)

    参考:Issuse Tracker

    【讨论】:

      【解决方案2】:

      你的例子在最新的 TypeScript 中编译得很好,没有错误:

      更多

      • 更新到typescript@next

      【讨论】:

        猜你喜欢
        • 2020-01-13
        • 1970-01-01
        • 2020-11-22
        • 2016-02-06
        • 2017-12-24
        • 2019-04-25
        • 2020-01-29
        • 1970-01-01
        • 2018-05-12
        相关资源
        最近更新 更多