Utility Type Exclude

I'd like to start by saying that I am doing this series to learn and understand better Typescript, so feel free to correct me or contact me.

Let's write and see how this utility type works under the hood.

Exclude

Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers (docs)

example:

type T0 = Exclude<"a" | "b" | "c", "a">; 

// type T0 = "b" | "c"

type T1 = Exclude<"a" | "b" | "c", "a" | "b">; 

//type T1 = "c"

type T2 = Exclude<string | number | (() => void), Function>; 

// type T2 = string | number

Now that we know how it should behave, let's write the type.

type MyExclude<Type, Exclude> =  Type extends Exclude ? never : Type

Here we check if Type extends Exclude then we should ignore it, remember we want to exclude that element, otherwise return the non-matching value.

There you go, it was a pretty simple one!

Thank you!