我正在使用Microsoft TypeScript-React-Starter并在npm start
期间得到了这个编译错误:
./src/index.tsx
(16,5): error TS2605: JSX element type 'App' is not a constructor function for JSX elements.
Types of property 'setState' are incompatible.
Type '{ <K extends never>(f: (prevState: null, props: {}) => Pick<null, K>, callback?: (() => any) | un...' is not assignable to type '{ <K extends never>(f: (prevState: {}, props: any) => Pick<{}, K>, callback?: (() => any) | undef...'.
Types of parameters 'f' and 'f' are incompatible.
Type '(prevState: {}, props: any) => Pick<{}, any>' is not assignable to type '(prevState: null, props: {}) => Pick<null, any>'.
Types of parameters 'prevState' and 'prevState' are incompatible.
Type 'null' is not assignable to type '{}'.
所以看起来我的setState
功能有不正确的签名,但我不知道如何解决它。这是我的代码:
class App extends React.Component<{}, null> {
render() {
return (
<div className="App">
...
</div>
);
}
}
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root') as HTMLElement
);
我在用:
node v6.11.0
npm v5.1.0
typescript v2.4.1
react v15.6.1
redux v3.7.1
react-redux v5.0.5
react-scripts-ts v2.3.2
更新:
我发现删除泛型类型<{}, null>
可以清除错误。但我仍然想知道为什么我会收到错误。
TLDR;国家不能为空。为它声明一个接口或声明它{}
答案在于@types/react
看看definition,州和道具都不是无效的。
当你将App
声明为class App extends React.Component<{}, null> {
时,你基本上说,“状态为null”。
现在setState
的类型取决于你为state指定的类型,它与lesser known version of the setState api发生冲突。 prevState
被声明为{}(默认情况下,因为没有指定state的接口),这与null不兼容,导致您看到的错误日志。
也许这个修复是不相关的,但我得到了相同的错误信息,没有<{}, null>
后class App extends React.Component
。这是我案例中的修复方法。
改变import React from 'react';
到import * as React from 'react';