Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Utility Types

TypeScript Required<T> utility type

Reference for TypeScript Required<T>: make every optional property mandatory, how the -? modifier works, and how it treats undefined and nested objects.

Required<T> builds a new object type from T in which every property is mandatory. Optional properties lose their ? marker, so a value of the new type must supply all of them. It is the mirror image of Partial<T>.

The usual use is after you have filled in defaults: the input type has optional fields, but once defaults are applied the result is guaranteed to have all of them, and Required<T> describes that result.

TypeScript
interface Options {
  retries?: number;
  verbose?: boolean;
}

type Complete = Required<Options>;
// { retries: number; verbose: boolean }

Try it

TypeScript Applying defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript A missing property is an error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

TypeScript
type Required<T> = {
  [P in keyof T]-?: T[P];
};
Name Description
T An object type (interface, alias, class instance type). Its properties are copied with the same names and value types.

Result: a mapped type with the same keys as T, all required. The -? modifier removes the optional flag from each key.

Edge cases: the -? modifier also strips the undefined that the ? itself added to the property type.

Usage notes

  • Shallow only. Required<T> changes the top level. A nested object such as config?: { port?: number } becomes config: { port?: number }; the inner port stays optional. Write a recursive mapped type if you need depth.
  • Strips undefined from optional properties. With strict on, y?: number has the type number | undefined when read. After Required, y is plain number. A property that is not optional but explicitly includes undefined (y: number | undefined) is unaffected: Required only touches the ? marker.
  • Readonly is preserved. Only the optional modifier is changed. Combine with Readonly<T> when you need both.
  • Does not validate at runtime. It is a compile-time promise only. Data from JSON or a network call must still be checked before you trust it.
  • Does not change index signatures. Required<Record<string, number>> is the same type as before.
  • Opposite: Partial<T> makes everything optional.
  • Available since TypeScript 2.8.