SwordInStone@lemmy.world to Programming@programming.dev · 3 days ago"How types make hard problems easy" (or at least reduce cognitive load over time)mayhul.comexternal-linkmessage-square12fedilinkarrow-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.comSwordInStone@lemmy.world to Programming@programming.dev · 3 days agomessage-square12fedilinkcross-posted to: [email protected]
minus-squaretracheslinkfedilinkEnglisharrow-up1·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-squareSwordInStone@lemmy.worldOPlinkfedilinkarrow-up5·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-squareSwordInStone@lemmy.worldOPlinkfedilinkarrow-up2·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