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?
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?
Have you actually implemented a custom type guard or just asserted size?
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 }
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 }
Hey cool, I learned something. Thanks!
<3
more context: https://stackoverflow.com/questions/56006111/is-it-possible-to-define-a-non-empty-array-type-in-typescript