Search code examples
reactjstypescriptreact-tsx

typescript not catching type mismatch (react TSX)


TypeScript & React newbie here. Why does TypeScript not yell at me for constructor(foo: string) input type not matching {foo: string}? (Note: one of them is a string, the other an object.)

TypeScript will happily compile this, and of course the resulting code will blow up. I tried to turn on all the options tsconfig.json has to offer. I'm using typescript 2.5.3.

Is there any way, like typescript config, code change, or anything else to harden the code to avoid this? Any ideas appreciated, my goal is to write stable code.

import * as React from 'react'; import * as ReactDOM from 'react-dom';

class App extends React.Component<{ foo: string }, { foo: string }> {
    // expects string
    constructor(foo: string) {
        super();
        this.state = {
            foo: foo
        }
    }
    render() {
        return <div>{this.state.foo}</div>
    }
}

// Passes object { foo: string }
ReactDOM.render(<App foo="foo" />, document.getElementById('root'))

EDIT: simplified question


Solution

  • You'll get the compiler complaints you're looking for if you remember to pass the props to super(). This is just part of extending React.Component, and should always be done.

    enter image description here