@SwordInStone@lemmy.world to Programming@programming.dev • 3 months ago"How types make hard problems easy" (or at least reduce cognitive load over time)mayhul.comexternal-linkmessage-square12fedilinkarrow-up149arrow-down10
arrow-up149arrow-down1external-link"How types make hard problems easy" (or at least reduce cognitive load over time)mayhul.com@SwordInStone@lemmy.world to Programming@programming.dev • 3 months agomessage-square12fedilink
minus-square@SwordInStone@lemmy.worldOPlinkfedilink4•3 months agoHave you actually implemented a custom type guard or just asserted size?
minus-square@traches@sh.itjust.workslinkfedilinkEnglish1•3 months 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@SwordInStone@lemmy.worldOPlinkfedilink5•3 months 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@traches@sh.itjust.workslinkfedilinkEnglish4•3 months agoHey cool, I learned something. Thanks!
minus-square@SwordInStone@lemmy.worldOPlinkfedilink1•2 months ago<3 more context: https://stackoverflow.com/questions/56006111/is-it-possible-to-define-a-non-empty-array-type-in-typescript
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