Nullable Values and Safe Access
Optional Chaining
Optional chaining reads through values that might be missing without throwing.
Optional Chaining
chaining.ts
type Profile = {
name: string;
contact?: {
email: string;
};
};
const hasContact: boolean = ;
const profile: Profile = hasContact
? { name: "Ada", contact: { email: "ada@example.com" } }
: { name: "Ada" };
const email: string | undefined = profile.contact?.email;
const message: string = email === undefined ? "no email" : email;
console.log(message);
type Profile = {
name: string;
contact?: {
email: string;
};
};
const hasContact: boolean = ;
const profile: Profile = hasContact
? { name: "Ada", contact: { email: "ada@example.com" } }
: { name: "Ada" };
const email: string | undefined = profile.contact?.email;
const message: string = email === undefined ? "no email" : email;
console.log(message);
optional chaining
The `?.` operator stops and returns `undefined` when the value on the left is missing.