Jimi
Jimi

Reputation: 1897

Reactjs, Typescript - Casting props in typescript - React Component

I'm using typescript 2.3.4 with React. I'm getting the error TS7006: Parameter 'props' implicitly has an 'any' type. Whats the correct way to cast props in typescript?

any help is appreciated.

interface State {
    name: string;
}

interface Props {

}


export class Profile extends React.Component<Props, State> {
    public state: State;
    public props: Props;
    constructor(props){
        super(props);
            this.state = {
               name: 'baz111'
            };
    }

    public render() {
        return (
            <section>
             <section>
                 <h3>profile 1</h3>
                 <div>baz</div>
             </section>
                <section>
                    <h3>profile 2</h3>
                    <div>{this.state.name}</div>
                </section>
            </section>
        )

    }
}

Upvotes: 2

Views: 3576

Answers (1)

Wazner
Wazner

Reputation: 3102

You're receiving this error because the parameter to your constructor doesn't have a type annotation. It should be:

constructor(props: Props) {
    super(props);
    this.state = {
       name: 'baz111'
    };
}

When a function parameter doesn't have a type annotation it will implicitly be typed any. When you have the noImplicitAny option on in your tsconfig.json file enabled, it will result in an error when such a case (your case) happens.

On an other note, you don't have to redeclare the state and props fields, you can just leave them out.

Upvotes: 6

Related Questions