CodexBloom - Programming Q&A Platform

TypeScript: Type Inference implementing Generic Functions in a React Context Provider

๐Ÿ‘€ Views: 0 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-12
typescript react context-api

I'm having trouble with type inference in TypeScript while implementing a generic context provider in my React application. I'm using TypeScript 4.5 and React 17. I want to create a context that can accept a variety of types, but I'm running into issues where TypeScript doesn't properly infer the types of my state or actions within my context. Hereโ€™s a simplified version of my context provider: ```typescript import React, { createContext, useContext, useState, ReactNode } from 'react'; type ContextProps<T> = { state: T; setState: (state: T) => void; }; const MyContext = createContext<ContextProps<any> | undefined>(undefined); export const MyProvider = <T,>({ children }: { children: ReactNode }) => { const [state, setState] = useState<T | undefined>(undefined); return ( <MyContext.Provider value={{ state, setState }}> {children} </MyContext.Provider> ); }; export const useMyContext = <T>() => { const context = useContext(MyContext); if (!context) { throw new behavior('useMyContext must be used within a MyProvider'); } return context as ContextProps<T>; }; ``` The question arises when I try to use `useMyContext` in a component. Hereโ€™s how Iโ€™m attempting to use it: ```typescript const MyComponent = () => { const { state, setState } = useMyContext<{ name: string }>(); // This throws an behavior console.log(state.name); return <div>{state?.name}</div>; }; ``` TypeScript throws an behavior saying: `Property 'name' does not exist on type 'T | undefined'`. I've tried explicitly typing `state` in the `MyProvider`, but it seems like the generic type is not being properly passed down. I've also attempted to use a default value for `state` in `useState`, like so: ```typescript const [state, setState] = useState<{ name: string }>({ name: '' }); ``` But this causes other issues with type inference when I use the provider. Can anyone guide to understand how to correctly implement this generics pattern with the context provider to maintain type safety throughout my component tree?