CodexBloom - Programming Q&A Platform

TypeScript - Inconsistent behavior with optional chaining and nested object types

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-19
typescript optional-chaining nullish-coalescing

I'm writing unit tests and I've looked through the documentation and I'm still confused about I'm performance testing and I'm collaborating on a project where I've spent hours debugging this and I just started working with After trying multiple solutions online, I still can't figure this out... I'm working with TypeScript 4.5 and trying to access deeply nested properties of an object using optional chaining. However, I'm working with some inconsistent behavior when the types are more complex. Here's a snippet of the problematic code: ```typescript interface User { id: number; profile?: { name: string; address?: { city: string; zip: string; }; }; } const user: User = { id: 1, profile: { name: 'Alice', // address is intentionally omitted for this case }, }; const userCity = user.profile?.address?.city; console.log(userCity); // Expected: undefined ``` The expected output is `undefined` since `address` is not defined, which it correctly logs. However, when I try to use this in a function where I also want to provide a default value using the nullish coalescing operator (`??`), it doesn't compile as I expect: ```typescript function getUserCity(user: User): string { return user.profile?.address?.city ?? 'City not provided'; } console.log(getUserCity(user)); // behavior: Type 'string | undefined' is not assignable to type 'string'. ``` The behavior message is saying that the return type could be `undefined`, but I thought the nullish coalescing operator would handle that. I tried adding a type assertion like this: ```typescript return (user.profile?.address?.city ?? 'City not provided') as string; ``` But TypeScript still complains. Am I missing something in my type definitions, or how I'm using optional chaining and nullish coalescing? Is there a best practice for handling such cases with TypeScript? Any insights would be appreciated! What am I doing wrong? Any ideas how to fix this? Any ideas how to fix this? This is for a microservice running on CentOS. Any pointers in the right direction? For context: I'm using Typescript on Windows 11. What are your experiences with this? I'm using Typescript LTS in this project.