DEV Community

Cover image for Advanced TypeScript Exercises - Answer 9
Pragmatic Maciej
Pragmatic Maciej

Posted on

Advanced TypeScript Exercises - Answer 9

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[]]
Enter fullscreen mode Exit fullscreen mode

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 };
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
nzdanny profile image
Daniel McDonald

Just wanted to say thank you so much for these exercises, they have been a great help in cementing everything I've been learning about TS!