Sub topic 2
Optional properties with ?
This chapter covers how a ? on a property changes the type of an object, how that differs from a property typed T | undefined, and which mistakes come up most often. It assumes you know basic TypeScript syntax, interfaces and type aliases, and union types including undefined. It also assumes you have "strict": true in your tsconfig.json. Without strictNullChecks, undefined disappears from most types and several behaviors below stop being visible.
Declaring an optional property
Put ? after the property name. An object of that type may then leave the property out.
interface User {
id: number;
name: string;
email?: string;
}
const a: User = { id: 1, name: "Ada" };
const b: User = { id: 2, name: "Grace", email: "[email protected]" };Both a and b are valid User values. The ? works the same way in type aliases, in inline object types, and in class bodies.
type Point = { x: number; y: number; label?: string };
function draw(p: { x: number; y: number; color?: string }): void {
console.log(p.x, p.y, p.color);
}
class Profile {
nickname?: string;
constructor(public readonly id: number) {}
}What the type means when you read it
Reading an optional property gives a type that includes undefined. For email?: string, the expression user.email has the type string | undefined. The compiler adds undefined because a missing property evaluates to undefined at runtime.
function shout(user: User): string {
return user.email.toUpperCase();
// Error: 'user.email' is possibly 'undefined'.
}You must handle the missing case before using the value. The next chapter covers narrowing, ?. and ?? in detail. For now, a plain check is enough.
function shoutSafe(user: User): string {
if (user.email === undefined) {
return "NO EMAIL";
}
return user.email.toUpperCase(); // narrowed to string
}The compiler tracks the check, so after the early return user.email is a string.
Optional is not the same as `T | undefined`
These two declarations look similar but describe different shapes.
interface A {
email?: string;
}
interface B {
email: string | undefined;
}
const a1: A = {}; // OK: the key may be absent
const a2: A = { email: undefined }; // OK by default
// const b1: B = {}; // Error: Property 'email' is missing in type '{}' but required in type 'B'.
const b2: B = { email: undefined }; // OK: the key is present, its value is undefinedThe difference is in the key, not the value:
email?: stringmeans the key may be absent. Reading it givesstring | undefined.email: string | undefinedmeans the key must be present. Its value may beundefined.
The second form is useful when you want callers to make a decision. A function that takes { email: string | undefined } forces every caller to write email explicitly, even if only to say undefined. That prevents forgetting the field by accident. The optional form is better when "not provided" is a normal state.
You can combine both: email?: string | undefined allows an absent key and an explicit undefined. Under the default settings this is the same as email?: string. It only matters when exactOptionalPropertyTypes is on, which a later chapter covers.
Absent, undefined, and what happens at runtime
By default, TypeScript treats "key is missing" and "key is set to undefined" as the same case in the type system. At runtime they are different.
interface User {
id: number;
name: string;
email?: string;
}
const missing: User = { id: 1, name: "Ada" };
const explicit: User = { id: 1, name: "Ada", email: undefined };
console.log("email" in missing); // false
console.log("email" in explicit); // true
console.log(Object.keys(explicit)); // [ 'id', 'name', 'email' ]
console.log(JSON.stringify(explicit)); // {"id":1,"name":"Ada"}in and Object.keys can tell the two apart. JSON.stringify drops properties whose value is undefined, so both objects serialize identically. If your code branches on "email" in user, an explicit undefined takes the "present" branch, and the value you then read is still undefined. For most code, check the value (user.email !== undefined) rather than the key.
placeholderOptional parameters, methods and tuple elements
The ? modifier appears in several places beyond object properties.
function greet(name: string, greeting?: string): string {
return `${greeting ?? "Hello"}, ${name}`;
}
greet("Ada");
greet("Ada", "Welcome");
interface Logger {
info(message: string): void;
debug?(message: string): void; // optional method
}
function run(logger: Logger): void {
logger.info("start");
logger.debug?.("details"); // call only if the method exists
}
type Range = [start: number, end?: number];
const r1: Range = [1];
const r2: Range = [1, 10];Rules to remember:
- An optional parameter must come after all required parameters.
function f(a?: string, b: number)is an error. - Inside the function, an optional parameter has type
T | undefined, just like an optional property. - An optional method
debug?(...)has type((message: string) => void) | undefined. Call it with?.(...). - In a tuple, optional elements must come last.
Defaults with destructuring
Destructuring can supply a default for a missing property. The default is used when the value is undefined, whether the key is absent or set explicitly.
function label(user: User): string {
const { name, email = "no email on file" } = user;
return `${name} <${email}>`; // email is string here
}After the default, email is a plain string. Defaults do not apply to null, so a property typed string | null still needs its own check.
Assignability rules
Optional properties affect which objects fit which types. Three rules cover most cases.
An object without the key can be assigned to a type where the key is optional. You saw this in const a: User = { id: 1, name: "Ada" }.
An object whose property is optional cannot be assigned to a type where that property is required.
interface Contactable {
email: string;
}
declare const u: User;
const c: Contactable = u;
// Error: Property 'email' is optional in type 'User' but required in type 'Contactable'.A type in which every property is optional is called a weak type. TypeScript refuses to assign a value to a weak type when the two share no properties at all. This catches typos.
interface Options {
verbose?: boolean;
color?: boolean;
}
const input = { vrebose: true };
const opts: Options = input;
// Error: Type '{ vrebose: boolean; }' has no properties in common with type 'Options'.Without this check, { vrebose: true } would match Options, because an empty object satisfies a type with only optional properties. Object literals written directly in the assignment also get excess property checking, which rejects unknown keys such as vrebose even when other known keys are present.
Common errors
The mistakes below account for most optional-property bugs in real code.
| Mistake | What happens | Fix |
|---|---|---|
| Using `user.email.length` without a check | Compile error under `strictNullChecks`, crash at runtime without it | Narrow, use `?.`, or give a default |
| Turning off `strict` to silence the error | `undefined` is dropped from the type and the crash returns | Keep `strictNullChecks` on and handle the case |
| Using `!` (non-null assertion) to force the type | Silences the compiler, still crashes if the value is missing | Use `!` only when you can prove the value exists |
| Checking `if (user.email)` for a string | Also rejects the empty string `""`, which is a valid value | Compare with `=== undefined` when `""` is meaningful |
| Treating `"email" in user` as "has a value" | True when the key holds `undefined` | Check the value, not the key |
| Making many properties optional to avoid writing values | Every reader must handle `undefined` and bugs move to runtime | Keep properties required unless absence is a real state |
The last row matters for design. An interface with many optional fields often hides several distinct shapes. If shippedAt and trackingNumber only exist once an order ships, two types describe the data better than one type with two optional fields.
interface PendingOrder {
status: "pending";
id: number;
}
interface ShippedOrder {
status: "shipped";
id: number;
shippedAt: Date;
trackingNumber: string;
}
type Order = PendingOrder | ShippedOrder;With the union, checking order.status === "shipped" makes shippedAt and trackingNumber available as required values. With optional fields, nothing ties the two together.
Exercises
Exercise
Given interface Item { sku: string; note?: string }, what is the type of item.note when item is an Item, and why does const x: Item = {} fail?
Show answer
item.note has type string | undefined, because a missing property reads as undefined. const x: Item = {} fails because sku is required and the empty object does not provide it. The optional note is not the cause of the error.
Exercise
What is the difference between interface P { id?: number } and interface Q { id: number | undefined } when you write const v = {} and assign it to each?
Show answer
const p: P = v compiles because the key id is allowed to be absent. const q: Q = v fails with "Property 'id' is missing" because Q requires the key to be present, even though its value may be undefined.
Exercise
A function has the signature function f(a?: string, b: number): void. What is wrong, and how do you fix it?
Show answer
A required parameter cannot follow an optional one. Either reorder to f(b: number, a?: string), or make b accept undefined with b: number | undefined so that callers pass it explicitly.
Exercise
Why does JSON.stringify({ id: 1, email: undefined }) produce the same text as JSON.stringify({ id: 1 }), and why can "email" in obj still differ between those two objects?
Show answer
JSON.stringify omits properties whose value is undefined, so both serialize to {"id":1}. The in operator tests whether the key exists on the object. The first object has the key email with value undefined, so "email" in obj is true there and false for the second object.