DEV Community

Cover image for Typescript Series - Exclude Utility Type
Sarmun Bustillo
Sarmun Bustillo

Posted on

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

Top comments (0)