Reputation: 229
What is the proper way to initialize state when using typescript and react. The following throws an error because obviously currentVehicle isn't allowed to be an empty object. What should the initial state be? What are best practicies?
interface State{
currentVehicle:Vehicle
}
export default class extends Component<Props, State> {
state:State={
currentVehicle:{}
}
}
Upvotes: 3
Views: 4491
Reputation: 1526
In this case i would define the type of currentVehicle as Vehicle or null and assign to it a null value on the initial state
interface State {
currentVehicle: Vehicle | null
}
export default class extends Component<Props, State> {
state: State = {
currentVehicle: null
}
}
A second option would be to define currentVehicle as an optional parameter. That way you don't have to initialise it.
interface State {
currentVehicle?: Vehicle // optional
}
export default class extends Component<Props, State> {
/** you only define your state without defining state.currentVehicle */
state: State = {}
}
Upvotes: 4