Exact Optional Property Types

Model absent versus explicitly undefined option fields: under exactOptionalPropertyTypes an optional property rejects undefined unless the union allows it.

TypescriptConfig Management

Code

typescriptsnippet
26 lines
// Enable "exactOptionalPropertyTypes": true in tsconfig, then:
// an optional property means "may be absent", NOT "may be undefined"
interface JobOptions {
  timeout?: number;
}

const defaults: JobOptions = {};
const explicit: JobOptions = { timeout: 3_000 };

// @ts-expect-error - undefined is not assignable to `timeout?: number` under the flag
const wrong: JobOptions = { timeout: undefined };

// To allow an explicit undefined, widen the type yourself
interface LooseOptions {
  timeout?: number | undefined;
}
const loose: LooseOptions = { timeout: undefined };

// Reading is unchanged: an absent property reads as undefined either way
function elapsedMs(options: JobOptions): number {
  return options.timeout ?? 30_000;
}

console.log("defaults:", elapsedMs(defaults));
console.log("explicit:", elapsedMs(explicit));
console.log("loose timeout:", loose.timeout); // widened interface keeps its own contract

Output

Captured from a sandboxed run of this snippet in the build pipeline.

defaults: 30000
explicit: 3000
loose timeout: undefined

The code in one pass

One function carries all the logic: elapsedMs.

Watch out for

  • Built-in APIs only; no supply chain needs vetting.

Putting it to use

Entry signature: function elapsedMs(options: JobOptions)

The output is self-labeling — defaults:, explicit:, loose timeout: — when the file runs.

Core lines

return options.timeout ?? 30_000;

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `elapsedMs` at load time.