Welcome back! I am Mihir, and in this lesson we will learn the Required utility type in TypeScript.
Required<T> makes every property in T required.
Basic Required Example
type UserSettings = {
theme?: string;
language?: string;
notifications?: boolean;
};
type CompleteSettings = Required<UserSettings>;CompleteSettings behaves like:
type CompleteSettings = {
theme: string;
language: string;
notifications: boolean;
};Using Required
const settings: Required<UserSettings> = {
theme: "dark",
language: "en",
notifications: true,
};Every property must be provided.
Invalid:
const settings: Required<UserSettings> = {
theme: "dark",
};Useful After Defaults
Required is useful when your app fills missing values with defaults.
type Config = {
apiUrl?: string;
timeout?: number;
};
function createConfig(config: Config): Required<Config> {
return {
apiUrl: config.apiUrl ?? "/api",
timeout: config.timeout ?? 5000,
};
}The returned config always has all properties.
Required Does Not Remove undefined from Value Types
type Example = {
value?: string | undefined;
};
type RequiredExample = Required<Example>;The property becomes required, but the value type can still include undefined if it was part of the original type.
Partial and Required Together
type DraftUser = Partial<User>;
type CompleteUser = Required<DraftUser>;This can be useful, but use it carefully. A required draft does not automatically mean the values are valid.
Quick Recap
Required<T>makes every property required.- It is the opposite of
Partial<T>. - It is useful after applying default values.
- It does not deeply validate runtime data.
- It does not always remove
undefinedfrom value types.
Next up, we will learn Readonly →.