Error TS2416 with state property in React Component using Typescript

1.2k views Asked by At

I am trying to compile a React (v16.13.1) component class in Typescript (v3.9.5) and have an error with the state field.

error TS2416: Property 'state' in type 'City' is not assignable to the same property in base type 'Component<CityProps, CityState, any>'.
  Type 'Readonly<CityState>' is missing the following properties from type '{ items: any; selected: any[]; }': items, selected

A Simple class example:

import React from 'react';

interface CityState {
    location: string;
}

interface CityProps {
    location: string;
}

export class City extends React.Component<CityProps, CityState> {

    state: Readonly<CityState> = {
        location: 'none'
    }

    constructor(props: CityProps) {
        super(props);
        this.setState({
            location: props.location
        });
    }

    render() {
        return (<p>{this.state.location}</p>);
    }
}

My tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src",
    "decs.d.ts"
  ]
}

Any suggestions on how to define state using this method of creating react components?

0

There are 0 answers