0

文件package.json

{
  "scripts": {
    "test": "tsc --project . --noEmit"
  },
  "dependencies": {
    "@types/react": "^16.7.6",
    "@types/react-dom": "^16.0.9",
    "react": "^16.6.3",
    "react-dom": "^16.6.3",
    "typescript": "^3.1.6"
  }
}

文件tsconfig.json

{
  "compilerOptions": {
    "lib": ["es2015", "dom"],
    "target": "es2015",
    "moduleResolution": "node",
    "jsx": "react",
    "strict": true
  }
}

文件test.tsx

import * as React from 'react'
import * as ReactDOM from 'react-dom'
import * as TestUtils from 'react-dom/test-utils'

interface Props {
  a: number
}

class Component extends React.Component<Props> {
  render () {
    return 'test'
  }
}

const div = TestUtils.renderIntoDocument(
  <div>
    <Component a={1} />
  </div>
) as React.Component

const component = TestUtils.findRenderedComponentWithType(div, Component)

运行tsc --project . --noEmit结果出现以下错误:

src/test.tsx:22:64 - error TS2345: Argument of type 'typeof Component' is not assignable to parameter of type 'ClassType<any, Component, ComponentClass<{}, any>>'.
  Type 'typeof Component' is not assignable to type 'ComponentClass<{}, any>'.
    Types of parameters 'props' and 'props' are incompatible.
      Type '{}' is not assignable to type 'Readonly<Props>'.
        Property 'a' is missing in type '{}'.

21 const component = TestUtils.findRenderedComponentWithType(div, Component)
                                                                  ~~~~~~~~~

这是一个错误吗?如果我禁用该--strict选项或省略<Props>in Component<Props>,它将成功编译。

4

1 回答 1

0

启用该选项时react-dom,类型声明未设计为工作。strictFunctionTypes我有一个更改来解决您看到的问题以及其他一些与strictFunctionTypes. 请参阅此答案,了解您可以使用我修改后的声明的可能方式,直到它们合并到 DefinedTyped 中。

于 2018-11-15T02:39:54.063 回答