我正在尝试使用 create-react-app --scripts-version=react-scripts-ts 命令编写一个支持 typescript 的 React 应用程序。
我不断看到此错误:
(23,15): error TS2345: Argument of type 'Props | undefined' is not assignable to parameter of type 'Props'. Type 'undefined' is not assignable to type 'Props'.
它来自的代码是这样的:
export class ScratchpadComponent extends React.Component<ScratchpadComponent.Props, ScratchpadComponent.State> {
constructor(props?: ScratchpadComponent.Props, context?: any) {
super(props, context);
this.submit = this.submit.bind(this);
}
不确定是什么原因导致此问题 - 我已四处搜索但没有太多关于如何解决此问题的线索?
更新:
如果我删除可选的 ?从构造函数签名,然后我开始看到这个错误:
18,11): error TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<Pick<Props, "dispatch" | "scratchPadActi...'.
Type '{}' is not assignable to type 'Readonly<Pick<Props, "dispatch" | "scratchPadActions" | "scratchData" | "errorMessage" | "errorDa...'.
Property 'dispatch' is missing in type '{}'.
最佳答案
父类(super class)构造函数需要 Props 作为其第一个参数。子类构造函数可以在没有任何参数的情况下调用,因为您将其声明为
constructor(props?: ScratchpadComponent.Props, context?: any)
而不是
constructor(props: ScratchpadComponent.Props, context?: any)
因此,如果调用者没有传递任何参数,则 props 是未定义的,并且您尝试将未定义传递给 super 构造函数,而 super 构造函数不接受未定义。
关于reactjs - 无法在 typescript 中的 constructor() 内部调用 super(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47970550/