简体   繁体   中英

What is the proper way of initializing nullable state in React/TypeScript apps?

What is the proper way to initialize initial empty(null) state in React, using TypeScript interfaces/types? For example, I have an interface:

interface IObject {
  name: string,
  age: number,
  info: IAnotherObject
}

and a simple component, where I want to define initial information state as null (w/o creating a class that implements my interface and shape default values for all properties), but with IObject interface

interface IState {
  information: null|IObject;
}

class App extends React.Component<{}, IState> {
 state = {
  information: null
 };

 componentDidMount() {
  // fetch some data and update `information` state
 }

 render() {
   <div>
    {this.state.information &&
    <div>
      <div>{this.state.information.name}</div>
      <div>//other object data</div>
    </div>
   </div>
 }

Do we have another way to initialize nullable state w/o using union type:

// worked way, but with union null type
interface IState {
  information: null|IObject;
}
// some another way(no union), but with initial `null` or `undefined`
interface IState {
  information: IObject;
}

state = {
 information: null
}

(it's seems not very "smart" for me to annotate with null every object which I want to have initial empty value)type object in state?

If you want to have initial empty state, you should to do this,

Mark information as empty,

interface IState {
  information?: IObject;
}

now you can initialize it as empty.

state = {}

You should rely on undefined instead of null for missing properties. From typescript style guide, ( link )

Use undefined. Do not use null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM