Rebuilding Typescript utility types

Jun 9, 2020 11:31 · 231 words · 2 minute read typescript

Rebuilding Typescript utility types img

If like me you ever wondered how to recreate some Typescript magic yourself the following tips are for you. There are many utility types so we will narrow down to some interesting ones.

Utility types we will reconstruct

  1. Partial
  2. Readonly
  3. Pick<T,K>
  4. Exclude<T,K>
  5. Extract<T,K>
  6. NonNullable

Things to note in the following examples is first : that typescript removes never so bascicaly type MyCustomType = string | never | boolean; will equal to string | boolean. Second : You should realy take time to study Conditional Types it is worth it :).

Partial and Readonly

The above gist is simple we define a type where each key in passed type is marked as optional by ? or readonly with readonly.

Pick

Creates a type with only picked keys that are passed as 2nd type argument, naturaly they must be existing keys of the main type passed as 1st argument.

Exclude and Extract

Here we use Conditional Type to figure out if second argument can extend first. If it does in case of MyExclude we do not want it and return never (which is omitted by typescript). MyExtract is just reversed MyExclude. I have also applied these types in object type checks in examples ObjWithExtract and ObjWithExclude.

NonNullable

This one is simple now.

Extract type from Array, Object or Flat (primitive) type

Stackblitz demo for our custom types:

Rebuilding Typescript utility typesdemo on Stackblitz