CodexBloom - Programming Q&A Platform

TypeScript: How to Manage Type Inference with Nested Conditional Types in a React Component?

👀 Views: 67 💬 Answers: 1 📅 Created: 2025-06-11
typescript react type-inference

I'm migrating some code and I've been banging my head against this for hours. I've searched everywhere and can't find a clear answer. I'm currently working on a React component that receives props where the shape of the props depends on the state of the application. Specifically, I have a configuration object that defines the types of data that the component should expect, but I'm struggling with TypeScript's type inference when using nested conditional types. Here’s a simplified version of what I have: ```typescript interface Config<T> { type: string; data: T; } type DataA = { id: number; name: string; }; type DataB = { id: number; age: number; }; type ConfigMap = { user: Config<DataA>; admin: Config<DataB>; }; type Props<K extends keyof ConfigMap> = { config: ConfigMap[K]; }; const MyComponent = <K extends keyof ConfigMap>({ config }: Props<K>) => { const { type, data } = config; if (type === 'user') { // Here data should be inferred as DataA console.log(data.name); } else if (type === 'admin') { // But here it throws an behavior because TypeScript want to infer data as DataB console.log(data.age); } return <div>{type}</div>; }; ``` When I try to access `data.age` in the `else if` block, TypeScript gives me an behavior, saying that `data` does not exist on the type `Config<DataA> | Config<DataB>`. I’ve attempted to use a type assertion like this: ```typescript if (type === 'admin') { const adminData = data as DataB; console.log(adminData.age); } ``` However, I feel like that’s not the right approach because I want to maintain type safety without unnecessary assertions. I also tried using a switch statement, but the scenario continues. What’s the correct way to ensure that TypeScript can infer the correct type for `data` based on the value of `type`? Any guidance on how to properly implement this pattern would be greatly appreciated! I'm working on a API that needs to handle this. I'd really appreciate any guidance on this. For context: I'm using Typescript on Ubuntu. This is part of a larger CLI tool I'm building.