Advanced TypeScript Exercises - Answer 9
Pragmatic Maciej
Posted on August 17, 2020
Hi folks. It was a while, sorry for such a big delay between next challenges. But here we are again 😁. The good news is also that the whole series was checked against newest TS and after few changes every code snippet works! So feel free to start with the whole series if you haven't yet, as its up to date with TS 4.0.
Now to our question - How to make NonEmptyArray
type which doesn't include []
value as a member.
Solution 1 - rest parameters in tuple types
type NonEmptyArray<T> = [T, ...T[]]
The solution is very clean and clear. What we do is - we explicitly set first element as T
and spread the rest as array of T
, in result the type force to have 0
index filled by T
. This is possible because of rest parameters in tuple types language feature.
Solution 2 - by intersection
type NonEmptyArray<T> = T[] & { 0: T };
Second solution in my own opinion is also great, we use simple intersection &
and create an array type T[]
which needs to have 0
index element as T
. In result first item of array cannot be empty.
Both code snippets are available in The Playground
This series will continue. If you want to know about new exciting questions from advanced TypeScript please follow me on dev.to and twitter.
Posted on August 17, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024