简体   繁体   中英

Error TS2339- Property 'x' does not exist on type 'Readonly<{}>'

I have a React+Typescript project working fine a day ago. When I tried to run it today suddenly 100's of erros of same type are occuring.

The type of error is as follows:

class Home extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
              x:true;
              y:true;
        };
     }
    toggleone = () => {
         this.setState({ x: !this.state.x })
    }
}

Previously these errors were not there and with no modifications they are occurred. Any suggestions?

React.Component is a generic interface with two type arguments, both with defaults: the props the component receives and the state the component maintains. State defaults to {} (no state items at all), but your component has two state members, x and y . So you'd need to do

class Home extends React.Component<{}, {x: boolean; y: boolean;}> {
    // ...
}

or as its own interface

interface HomeState {
    x: boolean;
    y: boolean;
}
class Home extends React.Component<{}, HomeState> {
    // ...
}

As for why this suddenly started happening: The code you've shown has no TypeScript type declarations or similar in it at all, suggesting it was originally JavaScript code and you added TypeScript later.


Side note: You'll also need to declare the type of props in the constructor :

constructor(props: {}) {
    // ...
}

...and fix the typos in the state initializer (the ; after true should be , ). (There's also no render method, but I'm assuming you just left it out to keep things minimal in the question.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM