Reputation: 13402
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
Upvotes: 1
Views: 904
Reputation: 11007
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.
Upvotes: 1
Reputation: 276191
Your concern :
// WRONG, to work, it should be:
// constructor(props Props) {
constructor(foo: string, bar: string) {
super();
}
is invalid because you can always inherit a class and provide your own constructor :
class A {
constructor(a: number) { }
}
class B extends A {
// ALLOWED
constructor(b: string) {
super(123)
}
}
Upvotes: 0