CodexBloom - Programming Q&A Platform

How to Type a Function that Conditionally Returns Different Object Shapes Based on Input in TypeScript?

👀 Views: 71 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
typescript type-annotations conditional-types

I've searched everywhere and can't find a clear answer. I'm working on a personal project and I'm working with TypeScript 4.9 and trying to create a function that can return different object shapes depending on the input parameters. Essentially, I have a function that takes a `flag` boolean and a `data` object, and based on the value of `flag`, it should return a different structure. But I'm struggling with how to correctly type this function to ensure that TypeScript can infer the return type accurately. Here's what I've tried so far: ```typescript interface UserData { id: number; name: string; } interface AdminData { id: number; name: string; admin: boolean; } function getUserData(flag: boolean, data: UserData | AdminData): UserData | AdminData { if (flag) { return { id: data.id, name: data.name, admin: true }; } else { return { id: data.id, name: data.name }; } } ``` When I call `getUserData(true, { id: 1, name: 'Alice' })`, TypeScript gives me an behavior because it expects `data` to have the `admin` property when I set `flag` to true. This is because I'm using a union type for `data`, but I need it to correctly infer the return type based on the `flag`. I've also tried using generics but couldn't quite get it to work. What is the best way to type this function so that TypeScript can understand that when `flag` is true, the object will have the `admin` property, and when it's false, it won't? Any suggestions on best practices or alternative approaches would be greatly appreciated! Is there a better approach? My development environment is Linux. Has anyone else encountered this?