Avatar ·

How to use optional chaining with arrays and functions in TypeScript?

Hi everyone! I'm new to TypeScript and ran into a problem when using optional chaining (?.). I know it helps safely access nested object properties, but I can't figure out how to properly apply it to arrays and functions. Here's an example with an array. I have a `user` object that may have a `posts` array. I want to get the first post if the array exists, otherwise return `undefined`: ```typescript interface User { name: string; posts?: Post[]; } interface Post { title: string; content: string; } const user: User = { name: "Alice" }; // Trying to get the first post const firstPost = user.posts?.[0]; // Error: "The left-hand side of an assignment expression may not be optional property access." ``` I tried `user.posts