DEV Community

Discussion on: Working with React context providers in Typescript

Collapse
 
arnaldobadin profile image
bardonolado • Edited

I was looking exactly for this, really good article! I was thinking, what if you use type guards to assert default values in useProvider() function?

export type ProviderType = Authentication;
export type ContextType = ProviderType | undefined;

...

/* assert type */
function isProviderType(value: ContextType): value is ProviderType {
    return value !== undefined;
}

export function userProvider() {
    const value = React.useContext<ContextType>(ProviderContext);
    if (!isProviderType(value)) throw new Error("The component using the ...");
    return value;
}
Enter fullscreen mode Exit fullscreen mode

Would be this a good approach?

Collapse
 
mitchkarajohn profile image
Dimitris Karagiannis

Yeah, that's definitely another approach to solve this problem! Depends on what you prefer, it's equally as valid, as far as I am concerned