PositiveGuy
PositiveGuy

Reputation: 20182

Typescript Error on super(): expected 1-2 arguments, but got 0

I don't know what I need to do to resolve this TS error:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

declare const Ink: any;

export default class TableOfContents extends Component <{ id: string }, { rendered: boolean }> {
    constructor() {
        super();
        this.state = { rendered: false };
    }

enter image description here

UPDATE:

I don't feel good about putting any here, what should it be? enter image description here

Upvotes: 10

Views: 12184

Answers (1)

Ajeet Shah
Ajeet Shah

Reputation: 19813

The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.

https://reactjs.org/docs/react-component.html#constructor

So, you need to write:

constructor(props) {
  super(props);
  this.state = { rendered: false };
}

You can also define interfaces for your props and state to fix all TS warnings and better intellisense:

interface IProps {
  id: string
}

interface IState {
  rendered: boolean
}

export default class TableOfContents extends Component<IProps, IState> {
  constructor(props: IProps) {
    super(props)
    this.state = {
      rendered: false,
    }
  }
}

If your editor complains and doesn't accept implicit any, you can set "noImplicitAny": false in compilerOptions in tsconfig file.

Upvotes: 14

Related Questions