Sub topic 1
Object types and their properties
Prerequisites
This chapter assumes basic TypeScript syntax, interfaces, type aliases, union types, and JavaScript objects. You should know that string | undefined means a value may be a string or undefined.
Object types and their properties
An object type describes the properties an object may have. Each property has a name and a type.
interface User {
id: number;
name: string;
email?: string;
}
const user: User = {
id: 1,
name: "Ada",
};The User interface requires id and name. It allows, but does not require, email.
Optional properties with `?`
A question mark after a property name makes that property optional. An object may omit the property entirely.
interface User {
id: number;
email?: string;
}
const first: User = { id: 1 };
const second: User = { id: 2, email: "[email protected]" };For reads, user.email has the type string | undefined. This is different from declaring email: string | undefined: that declaration still requires the email property to exist, although its value may be undefined.
Reading optional values: narrowing, ?. and ??
Because an optional value may be undefined, TypeScript requires a safe way to use it.
function contact(user: User): string {
return user.email?.toLowerCase() ?? "no email on file";
}
function printEmail(user: User): void {
if (user.email !== undefined) {
console.log(user.email.toUpperCase());
}
}Optional chaining (?.) stops when the value is null or undefined. Nullish coalescing (??) supplies a fallback only for null or undefined.
Missing versus undefined: `exactOptionalPropertyTypes`
By default, TypeScript often treats an optional property as though assigning undefined were allowed. Enable exactOptionalPropertyTypes when omission and explicit undefined have different meanings.
// tsconfig.json: { "compilerOptions": { "strict": true, "exactOptionalPropertyTypes": true } }
interface Settings {
theme?: string;
}
const a: Settings = {}; // OK
const b: Settings = { theme: undefined }; // ErrorWith this option, theme?: string means “the property may be absent.” If explicit undefined is also valid, write theme?: string | undefined.
Exercise
What type does reading an optional email?: string property produce, and how can you safely provide a fallback?
Show answer
It produces string | undefined. Use optional chaining with nullish coalescing, such as user.email?.toLowerCase() ?? "no email".