【问题标题】:Unable to call super() inside constructor() in typescript无法在打字稿中的构造函数()中调用 super()
【发布时间】:2017-12-25 17:03:17
【问题描述】:

我正在尝试使用 create-react-app --scripts-version=react-scripts-ts 命令编写一个支持打字稿的反应应用程序。

我一直看到这个错误:

(23,15): 错误 TS2345: 类型参数 'Props | undefined' 不可分配给“道具”类型的参数。 类型“未定义”不可分配给类型“道具”。

这是来自的代码是这样的:

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 '{}'.

【问题讨论】:

    标签: reactjs typescript create-react-app


    【解决方案1】:

    超类构造函数期望 Props 作为它的第一个参数。可以不带任何参数调用子类构造函数,因为您将其声明为

    constructor(props?: ScratchpadComponent.Props, context?: any)
    

    而不是像

    constructor(props: ScratchpadComponent.Props, context?: any)
    

    所以,如果调用者没有传递任何参数,那么 props 是未定义的,而您试图将 undefined 传递给不接受 undefined 的超级构造函数。

    【讨论】:

    • 嘿,我刚刚从组件定义中删除了可选签名,并用我现在看到的错误更新了我的问题。你知道如何摆脱这个错误吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    • 2022-01-23
    • 2018-04-08
    • 2012-05-17
    • 1970-01-01
    • 2013-02-18
    相关资源
    最近更新 更多