SwordInStone@lemmy.world to Programming@programming.dev · 5 days ago"How types make hard problems easy" (or at least reduce cognitive load over time)mayhul.comexternal-linkmessage-square12fedilinkarrow-up150arrow-down10
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 · 5 days agomessage-square12fedilink
minus-squaretraches@sh.itjust.workslinkfedilinkEnglisharrow-up1·5 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·5 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-squaretraches@sh.itjust.workslinkfedilinkEnglisharrow-up4·5 days agoHey cool, I learned something. Thanks!
minus-squareSwordInStone@lemmy.worldOPlinkfedilinkarrow-up1·4 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