3

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:{}
     }
  }
2

2 Answers 2

5

You can cast it:

state:State = {
    currentVehicle:{} as Vehicle
}
Sign up to request clarification or add additional context in comments.

2 Comments

The underlying value will still be an empty object which can cause errors during compile time if you try to access a prop in the empty object.
You'll only get a RefError if you try to access nested props, but top level props will just return undefined. Regardless though you should probably be null checking or at least initiating a state with all required values.
4

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 = {}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.