DEV Community

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

Posted on

8 3

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.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

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!

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️