> there is currently no sensible way to type a non empty array in Typescript
If we remove the "sensible" requirement:
type NonEmptyArray = [any, ...any[]]
Re:TypeScript 5.0
by triyambakam on Friday March 17, 2023 @01:59PM
(#35200531)
Or better:
type NonEmptyArray = [unknown, ...unknown[]];
const nea: NonEmptyArray = [];
// ^^^ Type '[]' is not assignable to type 'NonEmptyArray'.
// Source has 0 element(s) but target requires 1.
Re:TypeScript 5.0
by throwaway09432 on Saturday March 18, 2023 @01:30AM
(#35206420)
Can you map over this and preserve the NonEmptyArray type?
Re:TypeScript 5.0
by triyambakam on Sunday March 19, 2023 @03:00AM
(#35216711)
Do you mean pass in a type?
type NonEmptyArray<T> = [T, ...T[]];
Re:TypeScript 5.0
by throwaway09432 on Sunday March 19, 2023 @09:00AM
(#35218504)
I mean if I have a NonEmptyArray say xs, and I then xs.map(x=>2*x), will the result of this expression be a NonEmptyArray ?
Re:TypeScript 5.0
by triyambakam on Tuesday March 21, 2023 @08:28PM
(#35254947)
No, unfortunately it will just be number[] as the return type.
Personally I wish either Rescript or Purescript gained adoption instead.