Home > Mobile >  How to type initial value in React Context of object data fetched from API
How to type initial value in React Context of object data fetched from API

Time:05-09

I cannot figure out how to type properly initial value of createContext.

This is what I have in the interface of data:

lineSectionsDefectsDetailsData: LineSectionsDefectWarningDetailsType;

And that's precisely the type:

export type LineSectionsDefectWarningDetailsType = {
    id: string;
    timestamp: Date;
    type: string;
    imageUrl: string;
    lineId: string;
    kilometer: number;
    coordinates: [];
    description: string;
};

When I type initial value as:

lineSectionsDefectsDetailsData: undefined,

I get below comment from typescript

enter image description here

Can You please suggest how to type in such situation properly initial value ?

Thanks

CodePudding user response:

If undefined is a valid value for any type then you can use the | operator to define correct type definitions.

type LineSectionsDefectWarningDetailsType = {
  id: string;
  timestamp: Date;
  type: string;
  imageUrl: string;
  lineId: string;
  kilometer: number;
  coordinates: [];
  description: string;
} | undefined;
  • Related