TypeScript: Make stricter Required

When you have a type with optional props, then to make those props required you can use Required like so:

type TTypeWithOptional = { 
  a?: string;
  b: string | undefined;
  c?: string | null 
};

type TRequired = Required<TTypeWithOptional>;
/*
// result
type TRequired = {
    a: string;
    b: string | undefined;
    c: string | null;
}
*/Code language: TypeScript (typescript)

As you can see it did removed the optionality ?: but you may still, counterintuitively, encounter an “optional” prop, e.g. b being undefined. To solve this requirement you may want to use this strict required type:

export type TStrictRequired<T, E = null | undefined> = { 
  [P in keyof T]-?: Exclude<T[P], E> 
};Code language: TypeScript (typescript)

Which does the same the Required does but also filters out “optional” values by excluding undefined | null (that was my requirement).

type TStrict = TStrictRequired<TTypeWithOptional>;
/*
// result
type TStrict = {
    a: string;
    b: string;
    c: string;
}
*/Code language: TypeScript (typescript)

If you need null you can modify default behaviour, by using second generic parameter E and change it to exclude undefined only:

type TStrict = TStrictRequired<TTypeWithOptional, undefined>;
/*
// result
type TStrict = {
    a: string;
    b: string;
    c: string | null;
}
*/Code language: JavaScript (javascript)

This entry was posted in TypeScript and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.