Course contentsShow
← React
Lesson 2380 of 2,39651. TypeScript with React BasicsFree lesson

Context Type Inference from Provider

Leveraging TypeScript's inference to avoid repeating types when the Provider value is explicitly typed.

Context Type Inference from Provider

What you'll learn: How to let TypeScript automatically infer your context type from the Provider's value, eliminating redundant type declarations.

When you create a typed context, you often find yourself declaring the same type information twice: once in createContext<T>() and again when defining your Provider's value. TypeScript's inference can eliminate this duplication.

The Duplication Problem

You've been creating contexts like this:

type UserContextType = {
  user: User | null;
  login: (user: User) => void;
};

const UserContext = createContext<UserContextType | undefined>(undefined);

Then in your Provider, you define a value that matches UserContextType. You're effectively maintaining two sources of truth.

Let TypeScript Infer Instead

Define your Provider value first, then let TypeScript extract its type:

const UserContext = createContext<ReturnType<typeof useUserProvider> | undefined>(undefined);

function useUserProvider() {
  const [user, setUser] = useState<User | null>(null);
  
  const login = (user: User) => setUser(user);
  
  return { user, login };
}

function UserProvider({ children }: PropsWithChildren) {
  const value = useUserProvider();
  return <UserContext.Provider value={value}>{children}</UserContext.Provider>;
}

Now your context type is inferred from what useUserProvider() actually returns. Change the return value, and the context type updates automatically—no manual synchronization needed.

Think of It Like This

Instead of writing a contract first and implementing it later, you're implementing the functionality and deriving the contract from it. The Provider becomes your single source of truth.

Key Takeaway: Use ReturnType<typeof yourHook> to infer context types from Provider implementations, eliminating duplicate type declarations and keeping your types synchronized automatically.