Home > Blockchain >  Destructure given Array type into new types
Destructure given Array type into new types

Time:09-16

Let's say we have a type

type Args = [foo: string, bar: number, baz: number];

and we wanted to construct a new type

type NewArgs = [bar: number, baz: number];

from that Args type. Is that possible? I'm probably missing something. What I'm thinking of is something like "type destructuring"

type [Foo, ...NewArgs] = Args;

where

// Foo === string
// NewArgs === [bar: number, baz: number]

Edit:

I know that the following is possible but there must me a more clever way of doing it, right?

type NewArgs = [Args[1], Args[2]]

CodePudding user response:

The syntax is a bit unintuitive but this is how it's done:

type NewArgs = Args extends [any, ...infer U] ? U : never

See also Variadic tuple types

  • Related