DEV Community

Discussion on: Announcing TypeScript 4.1

Collapse
 
yoursunny profile image
Junxiao Shi • Edited

NDNts updated to TypeScript 4.1 on the day it came out.
ESLint didn't give me any trouble this time.
github.com/yoursunny/NDNts/commit/...

I had to insert many more exclamation marks for --noUncheckedIndexedAccess.
I wish there's a way to specify "this function returns an array of n items" where n is an argument.

I have this code in the test suite:

async function waitNClients(n: number): Promise<Socket[]> {
  // wait until n TCP clients are connected, then return them
}

const [sockA, sockB] = await waitNClients(2);
Enter fullscreen mode Exit fullscreen mode

Previously, this works fine. Now, I need to either put an exclamation mark next to everywhere sockA and sockB is used, or add a as [Socket, Socket]. This gets annoying when the sockets are used in many places, or there are many sockets so that the tuple type gets longer.
I wish I can specify the tuple type like Socket[6], or even better specify the function type like

async function waitNClients<N extends number>(n: N): Promise<Socket[N]>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
danielrosenwasser profile image
Daniel Rosenwasser

It's not so hard to do this with conditional types now in TypeScript 4.1!

type TupleOf<T, Length extends number> =
  number extends Length ? T[] : TupleOfHelper<[], T, Length>

type TupleOfHelper<Arr extends unknown[], T, Length extends number> =
  Arr["length"] extends Length ? Arr : TupleOfHelper<[T, ...Arr], T, Length>;

type Yadda = TupleOf<string, 2>
Enter fullscreen mode Exit fullscreen mode