Lars Nyström
Lars Nyström

Reputation: 6373

Is it possible to map the keys of a tuple to a union of number literals?

Let's say I have a tuple

type MyTuple = [string,number];

Now, I would like to get the union of all numeric keys for this tuple, i.e. 0 | 1. I can do this:

type MyKeys = Exclude<keyof MyTuple, keyof unknown[]>;

which will return the type "0" | "1", but that is a union of string literals. Is it possible to get a union of number literals instead?

Upvotes: 0

Views: 38

Answers (1)

Lars Nystr&#246;m
Lars Nystr&#246;m

Reputation: 6373

Ah, so I found the solution. Here it is:

type MyTuple = [string, string, string];
type KeysOfTuple = Exclude<Partial<MyTuple>['length'], MyTuple['length']>;
// KeysOfTuple = 0 | 2 | 1

Upvotes: 2

Related Questions