Does TypeScript support the ?. operator (optional chaining) and what is it called?
Hello everyone! I'm a beginner TypeScript developer and I've encountered a problem when working with nested objects. I have a User interface that contains an optional address field, and inside address there is an optional street field. When I try to get the street value, TypeScript throws an error if address is undefined. Here's an example of my code:
```typescript
interface Address {
street?: string;
city: string;
}
interface User {
name: string;
address?: Address;
}
const user: User = {
name: "Ivan"
};
// Error: Object is possibly 'undefined'
console.log(user.address.street);
```
I've heard that JavaScript has the ?. operator, which allows safe access to properties of nested objects. But I'm not sure if TypeScript supports it. If so
No answers yet.
Log in to leave an answer
Blogs