reactjs - Hur kan jag hämta typen på värdet i ett React-context?
Jag använder ett biblioteks kontext som inte exporterar typen av dess värde. Så här ser det ut:
type LocationContextObject = { /* some properties */ };
export type LocationContext = React.Context<LocationContextObject>;
Jag behöver komma åt LocationContextObject, är det möjligt att extrahera det från LocationContext?
Här är vad jag har gjort:
type LocationContextObject = ComponentProps<typeof LocationContext.Provider>['value'];
Det fungerar, men ser ut som en tillfällig lösning. Så jag undrar om det finns en mer elegant lösning.
Svar #1
import { ContextType } from 'react';
type LocationContextObject = ContextType<typeof LocationContext>;
Svar #2
Det är därför nyckelordet infer skapades.
type LocationContextObject =
LocationContext extends React.Context<infer U>
? U
: never
Lekplats
