Exact Optional Property Types
Model absent versus explicitly undefined option fields: under exactOptionalPropertyTypes an optional property rejects undefined unless the union allows it.
Code
// 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 contractOutput
Captured from a sandboxed run of this snippet in the build pipeline.
defaults: 30000
explicit: 3000
loose timeout: undefinedThe 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.