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 a Type to get the length of a tuple.
First, what it a tuple, tuple types allow you to express an array with a fixed number of elements whose types are known, but need not be the same.
Lets have a look to our tuple
const tesla = ['tesla', 'model 3', 'model X', 'model Y'] as const
Notice how we define it *as const * so it can't be modified.
Now we need to create a type that expects a tuple, and returns its length.
type Length<Type extends readonly unknown[]> = Type['length']
Let's break it down.
Length<Type extends readonly unknown[]>
You can read this as, Type extends an array of unknown type that its length won't change, remember for tuples we do know it's length, that is why we define the tuple variable as const so we cant modify it.
Type['length']
Lastly, we access the length property from our Type.
This one was an easy one
Thank you!
you can find me here My Twitter
Top comments (0)