Optional Property (TypeScript)

An optional property is one that may or may not be present on an object, marked with a `?` after its name. If you leave it out, its value is `undefined` rather than an error.

TypeScript

Marking a property optional with `?` tells TypeScript that omitting it is allowed. Required properties, by contrast, must always be supplied.

The same `?` works on function parameters to make an argument optional. When you read an optional property, TypeScript reminds you it might be `undefined`, nudging you to check before using it.

Syntax

interface T { name?: string; }

Examples

TypeScript

interface User {
  name: string;
  nickname?: string;
}

const a: User = { name: "Sam" };           // ok
const b: User = { name: "Sam", nickname: "S" }; // ok
console.log(a.nickname);

Output:

undefined

Learn it in a lesson

See also

Back to the Dictionary