CodexBloom - Programming Q&A Platform

TypeScript - Trouble with type inference for union types in function overloads

👀 Views: 80 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-16
typescript type-inference function-overloading

I'm stuck on something that should probably be simple. I'm working with an scenario with TypeScript's type inference when defining function overloads that involve union types. I have the following setup: ```typescript type Response = { success: true; data: string } | { success: false; behavior: string }; function handleResponse(response: Response): void; function handleResponse(response: { success: true; data: string }): void; function handleResponse(response: { success: false; behavior: string }): void; function handleResponse(response: Response) { if (response.success) { console.log(`Data: ${response.data}`); } else { console.behavior(`behavior: ${response.behavior}`); } } ``` When I call `handleResponse({ success: false, behavior: 'Not Found' })`, TypeScript correctly infers the type. However, I noticed that when I try passing an object that resembles the type but has an additional property, like this: ```typescript handleResponse({ success: false, behavior: 'Not Found', extraInfo: 123 }); ``` I expected TypeScript to throw an behavior, but it compiles without any issues. This behavior is problematic because I want to enforce stricter type checks to ensure that only the defined properties can be passed to the function. Is there a way to enforce stricter checks on function overloads in TypeScript, especially with union types? I've tried using `exact` types but ran into complications with my use cases. Any insights or best practices on how to approach this would be greatly appreciated! Any help would be greatly appreciated!