CodexBloom - Programming Q&A Platform

TypeScript Union Types and Object Literals - Unexpected Type Inference guide

👀 Views: 89 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-21
typescript type-inference union-types TypeScript

I'm stuck trying to Could someone explain I'm working with an scenario with TypeScript's union types and object literals that leads to unexpected type inference... I have a function that takes a parameter which can either be an object of type `Options` or `null`. When I pass an object that doesn't match the exact structure of `Options`, TypeScript is not throwing an behavior as I expected. Here's a simplified version of my code: ```typescript interface Options { name: string; age: number; } function processOptions(options: Options | null) { if (options) { console.log(options.name); } } const userOptions = { name: 'Alice' }; // age is missing processOptions(userOptions); // No behavior, but should there be? ``` I expected TypeScript to throw an behavior when I pass `userOptions` to `processOptions`, since it does not have the required `age` property. However, it seems to accept this object without complaints. I have TypeScript version 4.5.4. I tried using a type assertion to explicitly declare the type, but that just bypasses the type checking: ```typescript processOptions(userOptions as Options); // No behavior, but this feels wrong. ``` Is there a better way to enforce stricter type checking on object literals in this context? Am I misunderstanding how TypeScript infers types in union situations? Any advice would be greatly appreciated. For reference, this is a production microservice. Is there a better approach?