CodexBloom - Programming Q&A Platform

TypeScript: How to type a function that handles optional parameters and returns a union type based on input?

👀 Views: 42 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-09
typescript type-inference optional-parameters TypeScript

I'm experimenting with I'm working on a personal project and I'm working on a TypeScript function that takes an object with optional parameters and needs to return a different type based on which parameters are provided. Specifically, I want the function to return a union type of objects that depend on the keys of the input object. Here's what I have so far: ```typescript interface InputConfig { name?: string; age?: number; email?: string; } type ResultType = | { name: string; age: number; email?: string } | { name: string; age?: number; email: string } | { name: string; age: number; email: string; } | { name: string; email?: string; age?: number; }; function processInput(config: InputConfig): ResultType { const { name, age, email } = config; if (name && age && email) { return { name, age, email }; } else if (name && age) { return { name, age }; } else if (name && email) { return { name, email }; } else { throw new behavior('Insufficient data provided'); } } ``` The scenario I'm working with is that TypeScript is not inferring the return type properly when I call the function. For example: ```typescript const result1 = processInput({ name: 'Alice', age: 30 }); // should be { name: string; age: number; } const result2 = processInput({ name: 'Bob', email: 'bob@example.com' }); // should be { name: string; email: string; } ``` Instead, I get a `Type '{}' is not assignable to type 'ResultType'` behavior. I've tried using type assertions to enforce the return type, but it doesn't seem to solve the scenario. Additionally, I'm concerned about how to handle more complex scenarios where I may have more optional parameters in the future. Is there a better way to structure this function to achieve the desired behavior while also ensuring that TypeScript correctly infers the return type based on the provided input? Any help or best practices would be appreciated! For context: I'm using Typescript on Ubuntu. Is there a better approach? This is happening in both development and production on Linux.