TypeScript: Handling Optional Chaining with Union Types and Default Values in a Utility Function
After trying multiple solutions online, I still can't figure this out. I need help solving I'm trying to debug I'm working with an scenario where I need to create a utility function that takes an object with potentially nested properties and returns a default value if a specific property is not found. I'm using TypeScript 4.5 and I'm trying to leverage optional chaining and union types, but I keep running into types of errors. My goal is to safely access a deeply nested property without throwing errors, while also providing a default value when the property is undefined. Here's a simplified version of my utility function: ```typescript function getNestedProperty<T, K extends keyof T>(obj: T, key: K, defaultValue: any): any { return obj?.[key] ?? defaultValue; } ``` The question arises when I attempt to use this function with nested objects. For example: ```typescript type Config = { user?: { profile?: { name?: string; }; }; }; const config: Config = {}; const userName = getNestedProperty(config.user?.profile, 'name', 'Guest'); console.log(userName); // Expected: 'Guest' ``` However, I'm getting the following behavior: ``` Argument of type 'undefined' is not assignable to parameter of type 'Config'. ``` I've tried adjusting the types and using type assertions, but I need to seem to get it right. I'm also unsure if I'm using optional chaining correctly in this context. Should I be using a more complex type guard or a different approach altogether? Any suggestions would be greatly appreciated! The project is a desktop app built with Typescript. What are your experiences with this? For context: I'm using Typescript on Debian. I'm open to any suggestions. I've been using Typescript for about a year now. What would be the recommended way to handle this?