Hacker News new | ask | show | jobs
by NoInkling 1185 days ago
> there is currently no sensible way to type a non empty array in Typescript

If we remove the "sensible" requirement:

    type NonEmptyArray = [any, ...any[]]
1 comments

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.
Can you map over this and preserve the NonEmptyArray type?
Do you mean pass in a type?

    type NonEmptyArray<T> = [T, ...T[]];
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 ?
No, unfortunately it will just be number[] as the return type.