Comment by epolanski

Comment by epolanski 4 hours ago

4 replies

The version I was thinking when I wrote the comment is simpler

    type Flatten<T> = T extends Array<infer U> ? Flatten<U> : T
> The average Typescript dev likely doesn't need to understand recursive conditional types.

The average X dev in Y language doesn't need to understand Z is a poor argument in the context of writing better software.

furyofantares 2 hours ago

> The average X dev in Y language doesn't need to understand Z is a poor argument in the context of writing better software.

It's a good response to the claim that we'd be surprised at how many would fail to do this, though.

NooneAtAll3 3 hours ago

as a person that never touched JS and TS... what's the difference between the two answers?

  • granzymes 3 hours ago

    For one, the simple answer is incomplete. It gives the fully unwrapped type of the array but you still need something like

      type FlatArray<T extends unknown[]> = Flatten<T[number]>[]
    
    The main difference is that the first, rest logic in the complex version lets you maintain information TypeScript has about the length/positional types of the array. After flattening a 3-tuple of a number, boolean, and string array TypeScript can remember that the first index is a number, the second index is a boolean, and the remaining indices are strings. The second version of the type will give each index the type number | boolean | string.
  • ameliaquining 3 hours ago

    First one flattens a potentially-nested tuple type. E.g., FlatArr<[number, [boolean, string]]> is [number, boolean, string].

    Second one gets the element type of a potentially-nested array type. E.g., Flatten<number[][]> is number.

    For what it's worth, I've never needed to use either of these, though I've occasionally had other uses for slightly fancy TypeScript type magic.