2

In one of the codes in react documentation, the value defined in this.state is used in render() as

{this.state.name}

But when I implement that react code using typescript, it is giving error as:-

Property 'age' does not exist on type 'Readonly<{}>'.

The code in the typescript is:-

import * as React from "react";
class App2 extends React.Component{
    constructor(props:any)
    {
        super(props)
         this.state = {
            age : 0,
            name : "rohit"
        };
    }

    public render()
    {
        return(
                <h1>
                    {this.state.name}
                </h1>
        )
    }
}
export default App2;
0

1 Answer 1

2

When using Typescript you must provide types for props you accept and state of your class, so you shouldn't derive from plain React.Component (which defaults to React.Component<{}, {}> but instead declare template parameter to prop / state types you desire.

Stg like this should work for your case:

interface MyProps {
    something?: string;
}
interface MyState {
    age: 0;
    name: string;
}
class App2 extends React.Component<MyProps, MyState> {

```

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.