TypeScriptUtility types
Required<Type>
Creates a type where every property is required.
Example
#TypeScript
interface Options {
theme?: 'dark' | 'light'
pageSize?: number
}
const defaults: Required<Options> = { theme: 'dark', pageSize: 20 }
function resolve(options: Options): Required<Options> {
return { ...defaults, ...options }
}
const resolved = resolve({ pageSize: 50 })
console.log(resolved.theme, resolved.pageSize)Result
dark 50
Definition and usage
#Required<Type> does the opposite of Partial: it removes the question mark from every field, so each one becomes mandatory. The field’s type also loses the undefined variant that came from being optional.
It’s useful once a configuration is complete after merging with default values. A function accepts Partial<Config> and returns Required<Config>, so the rest of the code doesn’t need to check for missing fields.
Like other utility types, it works shallowly: nested objects keep their optional fields.
Syntax
#Syntax
type New = Required<Type>Type parameters
#Type
object type
The type whose fields should become required.
Good practices
#- The pattern of taking
Partialin and returningRequiredworks great for options with default values. - Watch out when spreading objects: an explicit
undefinedin the options will overwrite the default value.
Related entries
#Spotted a mistake or missing an example? Write to us.