Home > front end >  How can I retrieve the type of a React context's value?
How can I retrieve the type of a React context's value?

Time:08-25

I am using a library's context that doesn't export the type of its value. Here is what it looks like:

type LocationContextObject = { /* some properties */ };

export type LocationContext = React.Context<LocationContextObject>;

I need to access the LocationContextObject, is it possible to extract it from LocationContext?

Here is what I have done:

type LocationContextObject = ComponentProps<typeof LocationContext.Provider>['value'];

It does work but looks like a hack. So I am wondering if there's a more elegant solution.

CodePudding user response:

That's what the infer keyword was made for.

type LocationContextObject = 
  LocationContext extends React.Context<infer U> 
    ? U 
    : never

Playground

  • Related