Optional properties (?)

Properties that may, but don’t have to, show up in an object.

On this page

Example

#
TypeScript
interface Profile {
  name: string
  bio?: string
  level?: number
}

function card(profile: Profile): string {
  const bio = profile.bio ?? 'No bio yet'
  return `${profile.name} (level ${profile.level ?? 1}): ${bio}`
}

console.log(card({ name: 'Emma', level: 7 }))
console.log(card({ name: 'Jack', bio: 'Learning Python' }))
Result
Emma (level 7): No bio yet
Jack (level 1): Learning Python

Definition and usage

#

A question mark after a field name (avatar?: string) means the field is optional. An object without it is still valid, and the field’s type is effectively string | undefined.

Before using an optional field, the compiler requires you to check it exists. The most convenient way is the ?. and ?? operators, or a plain condition.

With the exactOptionalPropertyTypes option turned on, an optional field can’t be explicitly assigned undefined. That distinguishes “the field is missing” from “the field is set to undefined.”

Syntax

#
Syntax
interface Name {
  required: type
  optional?: type
}

Good practices

#
  • The easiest way to set default values for optional fields is the ?? operator, or destructuring with a default value.
  • To turn every field into optional, use the Partial<T> utility type.

Related entries

#

Spotted a mistake or missing an example? Write to us.