Required and Readonly

Make all properties required, or make them all readonly.

SyntaxRequired<T> Readonly<T>

Two more mapping utilities:

  • Required<T> β€” makes every property required, the opposite of Partial.
  • Readonly<T> β€” makes every property read-only so the object cannot be changed.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A save function converts a Partial<Draft> into Required<Draft> to ensure all fields are present before persisting.
  • A configuration validator asserts a Partial<Config> is Required<Config> after filling in all defaults.
  • A Readonly<Settings> type is used for an imported constants object to prevent any module from mutating it.

More examples

Required makes all props mandatory

Required<Options> removes the optionality from every field, making them all mandatory in the derived type.

Example Β· ts
interface Options {
  timeout?: number;
  retries?: number;
}

type StrictOptions = Required<Options>;
// { timeout: number; retries: number }

function run(opts: StrictOptions): void {
  console.log(`timeout=${opts.timeout} retries=${opts.retries}`);
}

Readonly freezes properties

Readonly<AppConfig> marks every property read-only so the compiler blocks any post-initialisation mutation.

Example Β· ts
interface AppConfig {
  apiUrl: string;
  maxRetries: number;
}

const config: Readonly<AppConfig> = {
  apiUrl: 'https://api.example.com',
  maxRetries: 3,
};

config.apiUrl = 'other'; // Error: Cannot assign to 'apiUrl' because it is a read-only property

Combining Required and Readonly

Nests Required inside Readonly to create an immutable, fully-required version of an optional draft type.

Example Β· ts
interface Draft {
  title?: string;
  body?: string;
}

type PublishedPost = Readonly<Required<Draft>>;
// { readonly title: string; readonly body: string }

const post: PublishedPost = { title: 'Hello', body: 'World' };
// post.title = 'Changed'; // Error

Discussion

  • Be the first to comment on this lesson.
Required and Readonly β€” TypeScript | SoundsCode