繁体   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