Make every property required with Required
Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.
A function takes options where everything is optional, then fills the gaps. After that point every field exists, and Required<Options> says so.
interface Options {
host?: string;
port?: number;
}
const defaults: Required<Options> = { host: 'localhost', port: 5432 };
function withDefaults(options: Options = {}): Required<Options> {
return { ...defaults, ...options };
}
function connect(options: Required<Options>): string {
return `${options.host}:${options.port}`;
}
console.log(connect(withDefaults({ port: 6543 })));localhost:6543Required<T> is the mapped type { [K in keyof T]-?: T[K] }. The -? modifier removes optionality, and without exactOptionalPropertyTypes it also removes the implicit undefined from the property's type. See the utility types page.
The type is a promise the code has to keep. withDefaults({ port: undefined }) spreads an explicit undefined over the default, and the result still claims port is a number. If callers can pass undefined on purpose, merge field by field with ?? instead of spreading.