Partial Options Merge With Required Defaults
Accept Partial<RetryOptions> from callers and merge over Required defaults, so every field of the resolved options object is guaranteed present.
Code
interface RetryOptions {
attempts: number;
backoffMs: number;
jitter: boolean;
}
// Required 保证合并结果每个字段都在:内部逻辑不必再判空
const DEFAULTS: Required<RetryOptions> = {
attempts: 3,
backoffMs: 200,
jitter: true,
};
// 调用方只传关心的字段:Partial 把所有属性变成可选
function resolveRetryOptions(partial: Partial<RetryOptions>): Required<RetryOptions> {
return { ...DEFAULTS, ...partial };
}
const merged = resolveRetryOptions({ attempts: 5 });
console.log('attempts:', merged.attempts, 'backoffMs:', merged.backoffMs, 'jitter:', merged.jitter);
console.log(resolveRetryOptions({ jitter: false, backoffMs: 50 }));
// 展开顺序即语义:partial 在后覆盖 DEFAULTS,缺省字段取默认值
console.log('defaults kept:', resolveRetryOptions({}).backoffMs);Output
Captured from a sandboxed run of this snippet in the build pipeline.
attempts: 5 backoffMs: 200 jitter: true
{ attempts: 3, backoffMs: 50, jitter: false }
defaults kept: 200How it works
Count the function resolveRetryOptions as the entire surface area of Partial Options Merge With Required Defaults.
The result comes back as an object carrying DEFAULTS.
Using it
Signature: function resolveRetryOptions(partial: Partial<RetryOptions>)
The demo output is labeled (attempts:, defaults kept:), so every line of output points back to the operation that emitted it.
The call returns DEFAULTS.
Key statements
return { ...DEFAULTS, ...partial };
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 `resolveRetryOptions` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `resolveRetryOptions` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.