"How types make hard problems easy" (or at least reduce cognitive load over time)
"How types make hard problems easy" (or at least reduce cognitive load over time)

mayhul.com
How types make hard problems easy

"How types make hard problems easy" (or at least reduce cognitive load over time)
How types make hard problems easy
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:
typescript
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!