reactjs - 无法在 typescript 中的 constructor() 内部调用 super()

标签 reactjs typescript create-react-app

我正在尝试使用 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/

相关文章:

javascript - 关节.shapes.uml.js : Uncaught TypeError: Cannot read property 'Generic' of undefined

javascript - 如何在 Typescript 和 React.js 中使用随机字段解析 JSON

reactjs - React CSS - 如何仅将 CSS 应用于特定页面

reactjs - npm 错误! 404 未找到 - GET https ://registry. npmjs.org/creat-react-app - 未找到

reactjs - Next.js 根据 router.asPath 更新状态

html - 在 Netlify 上部署后,Roboto 字体在 Safari 或移动浏览器中不起作用

reactjs - React AWS Amplify S3 Storage.put() No Credentials 错误

javascript - 单击react-native android时创建模式

angular - Prettier - 功能和评论之间的新线

node.js - 无法使用 create-react-app 生成项目