Codectionary / Developer documentation / TypeScript

Reading Optional Properties Safely

An optional property can be absent from an object.

What it is and why to use it

An optional property can be absent from an object. Under strict null checking, reading it produces a value that may be undefined. This lets a model describe incomplete profile data without pretending every object contains a usable string.

Common mistakes and limitations

Optional does not mean any value is accepted. A nickname still must be a string when supplied under exact optional checking. Reading a missing property and testing whether a key exists are different operations, especially when explicit undefined values are allowed.

Run this example

Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.

Terminal — compile and run

npx tsc example.ts --strict --target ES2022 --module commonjs
node example.js

Syntax

type Profile = { nickname?: string };

Examples

Reading Optional Properties Safely

Standalone TypeScript 5.8+ example; expected output is explained below.

type Profile = { name: string; nickname?: string };
function display(profile: Profile): string {
  return profile.nickname ?? profile.name;
}
console.log(display({ name: "John" }));
console.log(display({ name: "James", nickname: "Jay" }));
  1. The question mark makes nickname optional, while name remains required.
  2. The nullish fallback chooses name only when nickname is null or undefined; here its declared missing case is undefined.
  3. One profile omits the property and the other supplies it. This is useful for optional display preferences.
  4. Expected output: John Jay

Best practices

  • Optional does not mean any value is accepted. A nickname still must be a string when supplied under exact optional checking. Reading a missing property and testing whether a key exists are different operations, especially when explicit undefined values are allowed.
  • Keep external-input validation separate from compile-time type descriptions.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading