As I did research in the internet about some typescript topics I stumpled across this fantastic github repository.
Type<Challenge> is an open source collection of small typescript riddles. Why you should try to solve them you might ask? Because it is fun and you learn what crazy things you can do with the type sytem. And trust me. Your colleges will love you if you can provide fully typed generic functions, because the let you develop that much faster.
my learnings and my approach#
- Compare Types
- Extract Keys
Partially I used them, but the real magic happens if you combine them.
So I cheated and looked at the solutions of the first challenges which most of the time implement some basic utility types which are now included in the typescript typing system.
And boy, I learned a lot! I tried to put all the stuff in small cheatsheets sorted by the base challenge. It helped me to look into harder challenges which combine a lot of these technics. If you are not familiar with traversing trough objects, applying conditionals or iterate trough arrays in the typing system start with that. This will help a lot.
Note: To understand the examples and cheat sheats I build, you need a understanding of conditional, traversing and how to use the infer keyword.
working with arrays
Imagine you have a readonly const array of fruits.
const fruits = ['apple', 'bannana', 'cherry'] as const
Wouldn’t it be nice if we loop trough the array an extract all keys as an type? Easy:
const fruits = ['apple', 'bannana', 'cherry'] as const type Fruit = typeof fruits[number] // 'apple' | 'bannana' | 'cherry'
If you didn’t know the answer this question. Alone this simple solution is mindblowing. But wait there is more. You probably know some the Array Instance Methods like
push(). There are also more advanced technics like iterate trough an array with recursion. You can visit my typescript generics - array blog to see how to implement these methods in the typing system.
Perhaps you know the utilty type
Readonly<Type>. But how would you implement this generic by yourself? Or do you know how to implement the reverse? Removing all the readonly modifiers from a type? Check out my small but valueable cheatsheet about readonly.
Working on it!
dont reinvent the wheel in production#
There are some great solutions out there which help you to build complex types. Namely ts-toolbelt, utility-types, SimplyTyped which are great solution you should look into when it comes to production code.
solutions, but with explanations#
For all challenges you will find solutions in the same git repository. Most of the time this solutions do not have any explanation on the how and why. So if you want a little bit more background and explanation to this solutions, visit the amazing Michigan TypeScript Channel on youtube.
where to find the challenge to a solution in the cheat sheet.#
Check the source code of this page and you will find comments to the actual challenge, if there was one.