Luciano Battagliero

Optional vs. Required Properties in TypeScript

Published on

In TypeScript, the following two declarations look similar and are often treated as equivalent:

prop?: T
prop: T | undefined

They are not equivalent; they encode different intent. The difference is semantic, not syntactic.

Optional Properties

An optional property may be omitted.

Optional properties model the absence of a key as a valid state. They should be used only when it’s acceptable for the key to be missing.

type Props = {
  foo: number;
  bar?: string;
}

const baz: Props = { foo: 1 } // Valid
const qux: Props = { foo: 2, bar: 'lorem ipsum' } // Valid

Required Properties That May Be undefined

A required property cannot be omitted.

Required properties model the presence of a key whose value may be transient or unresolved during part of its lifecycle.

type Props = {
  foo: number;
  bar: string | undefined
}

const baz: Props = { foo: 1 } // Error
const qux: Props = { foo: 2, bar: undefined } // Valid
const xyz: Props = { foo: 3, bar: 'lorem ipsum' } // Valid

Intent Over Convenience

In practice, these two forms behave similarly, but that overlap does not make them interchangeable. The distinction is about communication: what the type expresses and what the API expects conceptually, even when the compiler permits similar assignments.

Using prop?: T because it’s shorter than writingprop: T | undefined is a misuse of optionality. Optionality should not be a shortcut for convenience. If a property must exist, the type should say so, even if that makes it slightly more verbose.

Types are part of an API. They communicate intent. Avoiding a few extra characters is not a good reason to make that intent less precise.

Filed under #technical

Subscribe to the RSS feed