Typescript Series - Exclude Utility Type

sarmunbustillo

Sarmun Bustillo

Posted on August 19, 2022

Typescript Series - Exclude Utility Type

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
Enter fullscreen mode Exit fullscreen mode

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

type MyExclude<Type, Exclude> =  Type extends Exclude 
? never : Type
Enter fullscreen mode Exit fullscreen mode

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!

you can find me here My Twitter

πŸ’– πŸ’ͺ πŸ™… 🚩
sarmunbustillo
Sarmun Bustillo

Posted on August 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related