Sub topic 4
Optional properties and parameters
This chapter assumes you know basic TypeScript types, interfaces, and union types. It also assumes strict (and so strictNullChecks) is on in your tsconfig.json, as set up earlier in this tutorial. The chapter covers how ? works on properties, parameters, and methods. It also covers how optional differs from "a union with undefined", and the errors you will meet.
What the question mark means
A ? after a property or parameter name marks it as optional. The caller or object literal may leave it out. With strictNullChecks on, TypeScript reads an optional member as if its type were the declared type plus undefined.
interface User {
name: string;
nickname?: string; // read as string | undefined
}
const a: User = { name: "Ada" };
const b: User = { name: "Ada", nickname: "ada99" };
const c: User = { name: "Ada", nickname: undefined };
// const d: User = { name: "Ada", nickname: null };
// Error: Type 'null' is not assignable to type 'string | undefined'.Two points from this example matter throughout the chapter:
- Leaving a property out and setting it to
undefinedare both allowed by default. nullis not included. If a field can legitimately benull, you must write it:nickname?: string | null.
Reading an optional property
When you read an optional property, the compiler gives you T | undefined. You must deal with the undefined case before using the value as a T.
interface User {
name: string;
nickname?: string;
}
function badge(user: User): string {
// return user.nickname.toUpperCase();
// Error: 'user.nickname' is possibly 'undefined'.
if (user.nickname !== undefined) {
return user.nickname.toUpperCase(); // narrowed to string
}
return user.name;
}You can also use the operators covered in later chapters, such as user.nickname?.toUpperCase() or user.nickname ?? user.name. The rule is the same in every case. An optional member is a nullable type, and you handle it as one.
Optional versus "T | undefined"
x?: T and x: T | undefined look similar, but they differ in one way. An optional member may be omitted. A member typed with | undefined must be present, even if its value is undefined.
interface A {
id?: number;
}
interface B {
id: number | undefined;
}
const a: A = {};
// const b: B = {};
// Error: Property 'id' is missing in type '{}' but required in type 'B'.
const b: B = { id: undefined };The same split applies to function parameters.
function withOptional(x?: number): void {}
function withUnion(x: number | undefined): void {}
withOptional();
withOptional(undefined);
withUnion(undefined);
// withUnion();
// Error: Expected 1 arguments, but got 0.Choose ? when "not provided" is a normal state. Choose T | undefined when you want callers to state the missing value explicitly. That is useful when a forgotten argument would be a bug.
Optional parameters
Optional parameters work like optional properties, with one extra rule: a required parameter cannot follow an optional one.
function greet(name: string, greeting?: string): string {
return `${greeting ?? "Hello"}, ${name}`;
}
greet("Ada"); // "Hello, Ada"
greet("Ada", "Hi"); // "Hi, Ada"
// function broken(a?: string, b: string): void {}
// Error: A required parameter cannot follow an optional parameter.Inside greet, the type of greeting is string | undefined, so the body must handle both cases. If a trailing parameter is optional, anything after it must be optional too, or you must restructure the signature.
Default values
A default value makes a parameter optional for callers. It also removes undefined from the type inside the function.
function greetWithDefault(name: string, greeting: string = "Hello"): string {
// greeting is string here, never undefined
return `${greeting}, ${name}`;
}
greetWithDefault("Ada"); // "Hello, Ada"
greetWithDefault("Ada", undefined); // "Hello, Ada"
// greetWithDefault("Ada", null);
// Error: Argument of type 'null' is not assignable to parameter of type 'string | undefined'.A default is applied only when the argument is undefined. It is never applied for null. That matches how ?? behaves, which a later chapter covers. A default parameter may appear before a required one, but then callers must pass undefined explicitly to get the default. Avoid that layout in public APIs.
Destructuring with defaults
Option objects are the most common place for optional properties. You can combine destructuring defaults with an optional-property interface.
interface ConnectOptions {
retries?: number;
timeout?: number | null; // null means "no timeout"
}
function connect({ retries = 3, timeout = 1000 }: ConnectOptions = {}): string {
// retries: number
// timeout: number | null (undefined removed, null kept)
return `retries=${retries}, timeout=${timeout}`;
}
connect(); // "retries=3, timeout=1000"
connect({ retries: 0 }); // "retries=0, timeout=1000"
connect({ timeout: null }); // "retries=3, timeout=null"The = {} after the parameter lets callers omit the whole object. A retry count of 0 is kept because defaults only replace undefined. A null timeout is kept because it is a deliberate value, and its type still includes null.
Optional methods
Methods can be optional too. The usual way to call one is with ?.().
interface Logger {
log(message: string): void;
flush?(): void;
}
function finish(logger: Logger): void {
logger.log("done");
logger.flush?.(); // calls flush only if it exists
}Without ?., writing logger.flush() fails with "Cannot invoke an object which is possibly 'undefined'."
Making members optional or required in bulk
Two built-in utility types change optionality across a whole type.
interface Settings {
theme: string;
fontSize: number;
}
type Draft = Partial<Settings>;
// { theme?: string; fontSize?: number }
type Complete = Required<Draft>;
// { theme: string; fontSize: number }
const draft: Draft = { theme: "dark" };
const full: Complete = { theme: "dark", fontSize: 14 };Required<T> removes the ? and also removes undefined that came from the optional marker. It is useful after you have filled in defaults and want a type that guarantees every field is present.
interface Settings {
theme: string;
fontSize: number;
}
const defaults: Settings = { theme: "light", fontSize: 12 };
function applySettings(partial: Partial<Settings>): Settings {
return { ...defaults, ...partial };
}This example has a trap. If partial contains { fontSize: undefined }, the spread copies the explicit undefined over the default. In the default configuration, TypeScript accepts that object under Partial<Settings>, so the result type claims fontSize is a number while the value is undefined. The exactOptionalPropertyTypes option, covered in a later chapter, closes this gap.
Checking whether a key exists
Because "missing" and "set to undefined" are both allowed, a value check cannot tell them apart. The in operator checks for the key itself.
interface Patch {
title?: string;
}
function describe(patch: Patch): string {
if ("title" in patch) {
return `title was provided: ${patch.title ?? "(undefined)"}`;
}
return "title was not provided";
}
describe({}); // "title was not provided"
describe({ title: undefined }); // "title was provided: (undefined)"Notice that after the in check, patch.title is still string | undefined. The check proves the key exists, not that its value is defined. Use this pattern only when the difference matters, for example when distinguishing "leave this field alone" from "clear this field" in an update request.
Common errors
| Message or symptom | Cause | Fix | Column | Column |
|---|---|---|---|---|
| `'x.y' is possibly 'undefined'` | Reading an optional property as if it were always present | Narrow with `if`, `?.`, or `??` | ||
| `Type 'null' is not assignable to type 'string \ | undefined'` | Passing `null` to an optional member | Add `\ | null` to the type, or pass `undefined` |
| `A required parameter cannot follow an optional parameter` | Parameter order | Reorder, make later parameters optional, or use an options object | ||
| `Expected 1 arguments, but got 0` | Parameter typed `T \ | undefined`, not optional | Change to `x?: T` or pass `undefined` | |
| `Property 'x' is missing in type '{}'` | Property typed `T \ | undefined` is not optional | Mark it `x?: T` or set it explicitly |
Summary of the rules
- With
strictNullChecks,x?: TmeansT | undefinedand allows the member to be omitted. nullis never included automatically. WriteT | nullwhere you need it.x: T | undefinedrequires the member or argument to be present.- A required parameter cannot follow an optional one.
- A default value applies only to
undefined, and it removesundefinedfrom the type inside the function. - Reading an optional member always gives a nullable type, which you must narrow or default.
Exercise
Given interface Profile { bio?: string | null }, which of these values can you assign to bio: "hi", undefined, null, or leaving it out? Then say what the type of bio is when you read it.
Show answer
All four are allowed. "hi" matches string, undefined matches the optional marker, null matches the explicit | null, and leaving the property out is what ? permits. When you read profile.bio, its type is string | null | undefined, so you must handle all three cases before using it as a string.
Exercise
What is the type of limit inside this function, and what does paginate(undefined) and paginate(0) use as the value of limit?
function paginate(limit: number = 20): number {
return limit;
}
Show answer
Inside the function, limit is number, because the default removes undefined. paginate(undefined) uses 20, since defaults apply to undefined. paginate(0) uses 0, since 0 is a real value and not undefined. Calling paginate(null) is a compile error under strictNullChecks.
Exercise
Why does const b: B = {} fail while const a: A = {} succeeds, when interface A { id?: number } and interface B { id: number | undefined }?
Show answer
id?: number lets the property be omitted, so {} is a valid A. In B, the property is required and only its value may be undefined, so {} is missing id. You would have to write { id: undefined }.