编译时无法识别Typescript React类型

时间:2019-07-16 00:47:48

标签: reactjs typescript

我正在尝试使用打字稿将应用程序转换为React。我让它在普通ES2015中正常运行。但是,现在我已经在图片中添加了打字稿,因此gulp在尝试编译.tsx文件时会抛出错误:

error TS2339: Property 'setState' does not exist on type 'App'.

即使是经过精简的测试组件也会因以下原因而失败:

error TS2605: JSX element type 'App' is not a constructor function for JSX elements.
  Type 'App' is missing the following properties from type 'ElementClass': context, setState, forceUpdate, props, refs
import * as React from "../libs/noinject/react.development";
import * as ReactDOM from "../libs/noinject/react-dom.development";

interface State {foo: string}
export class App extends React.Component<{}, State> {
  state: State
  constructor(props: any) {
    super(props);
    this.state = {
      foo: 'bar',
    };
  }
  render() {
    return (
      <div>
        {this.state.foo}
      </div>
    );
  }
}

document.addEventListener('DOMContentLoaded', function () {
  ReactDOM.render(<App />, document.getElementById('app-root'));
});

很显然,打字稿编译器无法识别React.Component类型。我正在使用gulp-typescript通过以下编译器选项进行编译:

{
    'lib': ['ES2018', 'DOM'],
    'target': 'es6',
    'module': 'none',
    'moduleResolution': 'node',
    'jsx': 'react',
    'types': [
      'react',
      'react-dom',
    ],
  }

节点模块@types/react@types/react-dom已安装并明确使用,因为立即删除它们会导致TS编译步骤因抱怨找不到类型而失败。

请注意,我在vscode intellisense中也得到了波浪状的红色下划线,并且出现了相同的错误(Type 'App' is missing the following properties...)。

有什么作用?

2 个答案:

答案 0 :(得分:1)

通过将tsconfig.json添加到具有以下内容的根目录中,我可以使您的设置生效:

{
  "compilerOptions": {
    "noImplicitAny": true,
    "lib": ["es6", "dom"],
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "jsx": "react",
    "types": [
      "react",
      "react-dom"
    ]
  },
  "exclude": ["node_modules"]
}

然后,在gulpfile.js中,我有以下内容:

var gulp = require('gulp');
var ts = require('gulp-typescript');
var project = ts.createProject('./tsconfig.json');

gulp.task('default', function () {
    return gulp.src('./index.tsx')
        .pipe(project())
        .pipe(gulp.dest("dist/"));
});

使用gulp-typescript以及您说过的其他代码和软件包进行测试,我得以将其编译并在index.js文件夹中创建了dist/文件。

答案 1 :(得分:0)

所以问题是我需要从.js文件中导入React,而我只需要导入“反应”,而打字稿2+知道如何在node_modules/@types中查找。换句话说,这些行:

import * as React from "../libs/noinject/react.development";
import * as ReactDOM from "../libs/noinject/react-dom.development";

应为:

import * as React from "react";
import * as ReactDOM from "react-dom";