Eric Grossman
Eric Grossman

Reputation: 229

How to set initial React state in typescript?

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

Answers (2)

ehutchllew
ehutchllew

Reputation: 958

You can cast it:

state:State = {
    currentVehicle:{} as Vehicle
}

Upvotes: 5

Daniel Gabor
Daniel Gabor

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

Related Questions