TypeScript: Handling non-null assertions with optional chaining and arrays
I'm trying to figure out I'm stuck on something that should probably be simple. I've been banging my head against this for hours. I'm having trouble with TypeScript's non-null assertion operator when used in combination with optional chaining and arrays. I have a scenario where I fetch user data from an API that returns either a user object or null. The user object has a property `addresses`, which is an array that can also be undefined. My goal is to access the first address of the user if it exists. Hereโs the code Iโve written: ```typescript interface User { id: number; addresses?: Address[]; } interface Address { street: string; city: string; } async function getUser(userId: number): Promise<User | null> { // Simulating an API call return await fetch(`/api/users/${userId}`).then(response => response.json()); } async function displayUserAddress(userId: number) { const user = await getUser(userId); const firstAddress = user?.addresses![0]; // Using non-null assertion here console.log(firstAddress); } ``` When I run this code, I get a TypeScript error: ``` Object is possibly 'undefined'. ``` I thought that by using the non-null assertion operator (`!`) after `addresses`, I would be telling TypeScript that `addresses` is definitely defined when I access the first element. But it seems like TypeScript is not convinced and still produces this error. I've also tried using optional chaining on the array like this: ```typescript const firstAddress = user?.addresses?.[0]; ``` This works, but I'm not sure if it's the best practice, since it returns `undefined` if `addresses` is not defined, while my initial intention was to ensure that `firstAddress` is either an `Address` or throws an error if it doesnโt exist. How can I handle this situation properly while maintaining type safety and clarity in my code? This is part of a larger API I'm building. What am I doing wrong? I appreciate any insights!