martin36
martin36

Reputation: 2363

Typescript - Setting the type for a null property, when defining the initial state in Redux

After defining the initial state for the reducers in Redux, I want to get the type for the initial state so it gets automatically updated if I add any properties to the state.

Here is my definition of the initial state

let initialState = {
  food: {
    data: null,
    fetching: false,
    fetched: false,
    error: null
  }
}

Then I extract the type definitions from this state

export type StoreState = typeof initialState;

The food.data property should be of the type Food, which is defined as follows:

export interface Food {
  fdcId: number
  description: string
  nutrients: Array<Nutrient>
}

export interface Nutrient {
  name: string
  unitName: string
  amount: number
}

By default food.data gets defined as the type never when assigning it null in the initial state. That way when I want to access the property nutrients of it I get an error saying Property 'nutrients' does not exist on type 'never'.

Defining food.data with null as Food won't work because that also give errors.

If I define food.data with {} as Food, then I won't be able to set it to null in the reducer.

So my question then is, how can I define the property food.data such that when I get the typeof for the initial state it knows that food.data is of the type Food and such that food.data still can be null?

Upvotes: 3

Views: 2816

Answers (1)

martin36
martin36

Reputation: 2363

By defining the data as null or Food, I got it to work

let initialState = {
  food: {
    data: null as (null | Food),
    fetching: false,
    fetched: false,
    error: null
  },
}

Upvotes: 3

Related Questions