DEV Community

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

Posted on

10 2

Advanced TypeScript Exercises - Question 9

Short but very interesting question ahead of you. Write a type which will represent not empty array NonEmptyArray. Type should behave in the same way as original Array is behaving, with this difference that empty array is a value which is not a valid member of NonEmptyArray

type NonEmptyArray<T> = /* your type level code here 💪 */
const a: NonEmptyArray<string> = [] // should be compilation error 🛑
const b: NonEmptyArray<string> = ['Hi TS'] // should be ok! 👌
Enter fullscreen mode Exit fullscreen mode

Watch out, there is not one possible solution. How many solutions can you make? Post your answers in comments (preferred links to the playground). Have fun! Answer will be published soon!

This series will continue. If you want to know about new exciting questions from advanced TypeScript please follow me on dev.to and twitter.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (5)

Collapse
 
jfet97 profile image
Andrea Simone Costa

My first solution :D

type NEA<T> = [T, ...T[]]
Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
dwjohnston profile image
David Johnston

So why doesn't this work for an array of length 2?

Collapse
 
akashkava profile image
Akash Kava

TypeScript has endless magic, doesn’t stop to amaze me.

Collapse
 
chrismatheson profile image
Chris Matheson

@macsikora I actually added a NonEmptyArray type to my codebase a while ago. It’s been useful, but not as much as I had hopped.

Have you found this type useful in a real world setting?

From memory the main “problem” was things like ‘map’ don’t “flow” the underlying type through...

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. ❤️