Typescript Series - Exclude Utility Type
Sarmun Bustillo
Posted on August 19, 2022
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!
you can find me here My Twitter
π πͺ π
π©
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
javascript How I Created Vanilla Calendar Pro β A Lightweight and Flexible JavaScript Calendar with TypeScript
November 28, 2024
typescript π₯ Why TypeScript is the Go-To Language for Modern Web Development π₯
October 16, 2024