Skip to content
jshacks.dev
TypeScript

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.

1 min read
Summarize in AI

A function takes options where everything is optional, then fills the gaps. After that point every field exists, and Required<Options> says so.

connect.tsTypeScript
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 })));
Text
localhost:6543

Required<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.

Share

More snippets

TypeScript

Declare types for an untyped module

Write a small .d.ts file with declare module so an untyped package gets real function signatures, instead of an implicit any error. TypeScript 5.

1 min read
TypeScript

Type Node.js streams

Type a Node.js Transform stream and pipe it with the promise version of pipeline so chunk types and errors are checked. Needs @types/node 22 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.