Required and Readonly
Make all properties required, or make them all readonly.
Syntax
Required<T> Readonly<T>Two more mapping utilities:
Required<T>β makes every property required, the opposite ofPartial.Readonly<T>β makes every property read-only so the object cannot be changed.
Example
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.
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.
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 propertyCombining Required and Readonly
Nests Required inside Readonly to create an immutable, fully-required version of an optional draft type.
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