@SwordInStone to [email protected] • 3 days ago"How types make hard problems easy" (or at least reduce cognitive load over time)mayhul.comexternal-linkmessage-square12arrow-up150arrow-down10cross-posted to: [email protected]
arrow-up150arrow-down1external-link"How types make hard problems easy" (or at least reduce cognitive load over time)mayhul.com@SwordInStone to [email protected] • 3 days agomessage-square12cross-posted to: [email protected]
minus-square@[email protected]linkfedilinkEnglish1•3 days agoThis 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 }
minus-square@SwordInStoneOPlink5•3 days agotype 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 }
minus-square@SwordInStoneOPlink2•3 days ago<3 more context: https://stackoverflow.com/questions/56006111/is-it-possible-to-define-a-non-empty-array-type-in-typescript
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