§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 | undefinedBut 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 might be undefined, or might start undefined and resolve later.
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' } // ValidIn practice, these two forms behave similarly, but that overlap does not make them interchangeable. Writing prop?: T is shorter than prop: T | undefined, but choosing one over the other for convenience alone makes the type less precise.
Types are part of an API; they must be precise and communicate intent.