this post was submitted on 05 Jan 2025
51 points (100.0% liked)

Programming

17759 readers
835 users here now

Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!

Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.

Hope you enjoy the instance!

Rules

Rules

  • Follow the programming.dev instance rules
  • Keep content related to programming in some way
  • If you're posting long videos try to add in some form of tldr for those who don't want to watch videos

Wormhole

Follow the wormhole through a path of communities [email protected]



founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 2 points 3 days ago* (last edited 3 days ago) (1 children)

I’ve tried to use that NonEmptyArray type in the past and it was a real pain in the ass getting the type checker to believe that no, for realsies this array is not empty I just checked the length two lines ago. Is there some trick I don’t know or has it gotten smarter about that in recent updates?

[–] [email protected] 4 points 3 days ago (1 children)

Have you actually implemented a custom type guard or just asserted size?

[–] [email protected] 1 points 2 days ago (1 children)

This is what I'm talking about:

Code for copy-pasting:

type NonEmptyArray<T> = [T, ...T[]];

function neverEmpty<T>(array: T[]): NonEmptyArray<T> | null {  
    if (array.length === 0) return null

    return array
}
[–] [email protected] 5 points 2 days ago (1 children)
type NonEmptyArray<T> = [T, ...T[]];

function isNonEmptyArray<T>(arr: T[]): arr is NonEmptyArray<T> {
    return arr.length > 0;
}

function neverEmpty<T>(array: T[]): NonEmptyArray<T> | null {  
    if (!isNonEmptyArray(array)) return null

    return array
}