These days, I want to deep dive into TypeScript's type system. By mastering this, you can become a better developer.
At the end of this article, there will be a tip to improve it.
So, take this example:
Implement a generic First that takes an Array T and returns its first element’s type.
For example:
type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]
type head1 = First<arr1> // expected to be 'a'
type head2 = First<arr2> // expected to be 3
A good way to do it is using Typescript's infer
keyword.
You use the infer
keyword inside a conditional type
You can imagine this as:
Hey infer
, guess the type and give it a name that I can use later.
Well, to solve the previous example, you can use infer
like this:
type First<T extends unknown[]> = T extends [infer U, ...unknown[]] ? U : never
Here we say:
The First type accepts a generic T that extends an unknown array.
Then it checks if T matches a tuple whose first element can be inferred as U.
If it does, it returns U (the type of the first element), otherwise it returns never.
So we can use the First
type like this
type arr2 = [3, 2, 1]
type head2 = First<arr2> // 3
Now, my wise promise ✨
If you want to become a stronger developer you have to practice on this.
Here is an excellent repo to do it.
Thanks. See you next time 👋🏻
Top comments (0)