CodexBloom - Programming Q&A Platform

TypeScript: Getting 'undefined' on accessing a property of nested object in async function

👀 Views: 96 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-09
typescript angular rxjs TypeScript

I'm working through a tutorial and I'm attempting to set up Quick question that's been bugging me - I'm stuck trying to I've looked through the documentation and I'm still confused about I've been struggling with this for a few days now and could really use some help... I'm facing an issue in my TypeScript application where I get `undefined` when trying to access a property of a nested object that is being populated asynchronously. I'm using TypeScript 4.7 with Angular 14, and I have a service that fetches user data which includes a nested profile object. Here's a simplified version of the code: ```typescript interface UserProfile { name: string; age: number; address?: { street: string; city: string; }; } interface User { id: number; profile: UserProfile; } @Injectable({ providedIn: 'root' }) export class UserService { constructor(private http: HttpClient) {} getUser(userId: number): Observable<User> { return this.http.get<User>(`/api/users/${userId}`); } } @Component({ selector: 'app-user', templateUrl: './user.component.html' }) export class UserComponent implements OnInit { user: User | undefined; constructor(private userService: UserService) {} ngOnInit() { this.userService.getUser(1).subscribe((data) => { this.user = data; console.log(this.user.profile.address.city); // This line throws 'undefined' }); } } ``` In my API response, the `address` property sometimes comes back as `null`, and I'm not sure how to handle cases where it may not be there before accessing its properties. I tried using optional chaining like this: ```typescript console.log(this.user?.profile?.address?.city); ``` However, it still returns `undefined` if `address` is not present, which is expected, but I was hoping to handle this scenario more gracefully or at least avoid runtime errors. I also attempted to add a check before accessing it: ```typescript if (this.user && this.user.profile && this.user.profile.address) { console.log(this.user.profile.address.city); } else { console.log('Address not available'); } ``` This feels cumbersome. Is there a better pattern or approach for dealing with optional nested properties in TypeScript, especially when dealing with asynchronous data fetching? Any best practices or design patterns I should consider to avoid these pitfalls? For context: I'm using Typescript on Linux. Thanks in advance! Any advice would be much appreciated. Thanks, I really appreciate it! Could this be a known issue? The stack includes Typescript and several other technologies. This is part of a larger web app I'm building. What's the best practice here?