TypeScript: Difficulty with creating a union type from a complex object with optional properties
I'm sure I'm missing something obvious here, but I'm not sure how to approach I've been struggling with this for a few days now and could really use some help. I've been struggling with this for a few days now and could really use some help. I'm trying to create a union type in TypeScript that combines multiple object types, but I'm running into issues with optional properties. My goal is to allow certain properties to be optional in one of the object types but still enforce type safety overall. Here's what I've defined so far: ```typescript interface Base { id: number; name: string; } interface TypeA extends Base { value: string; } interface TypeB extends Base { value?: number; } type UnionType = TypeA | TypeB; ``` Now, when I try to use this union type in a function, I encounter issues when TypeScript expects `value` to be present: ```typescript function processValue(param: UnionType) { console.log(param.value.toFixed(2)); // behavior here } ``` TypeScript throws the behavior: `Property 'toFixed' does not exist on type 'string | number | undefined'.` This is frustrating because I thought the optional property would allow for `value` to be either a string (in `TypeA`) or a number (in `TypeB`). I've tried adding type guards to distinguish between the types, but I keep working with issues: ```typescript function processValue(param: UnionType) { if (typeof param.value === 'number') { console.log(param.value.toFixed(2)); } else { // Here, TypeScript still sees 'value' as possibly undefined console.log(param.value); } } ``` This results in `Type 'string | undefined' is not assignable to parameter of type 'string'.` I am unsure how to structure my code to handle these optional properties correctly while keeping TypeScript's type safety. Is there a recommended way to handle this situation? Any insights on how to properly type this union while using optional properties would be greatly appreciated! My development environment is Linux. What am I doing wrong? My team is using Typescript for this microservice.