Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a tuple type to a union?

How to map a tuple generic type to a union type?

type NeededUnionType<T> = T[keyof T]; // Includes all the Array properties values
  
const value: NeededUnionType<[7, string]> = 2; // This should not be allowed (2 is the tuple length)

Expected type: 7 | string

like image 429
user1304988 Avatar asked Dec 08 '19 20:12

user1304988


People also ask

What is type in tuple?

A tuple is a TypeScript type that works like an array with some special considerations: The number of elements of the array is fixed. The type of the elements is known. The type of the elements of the array need not be the same.

What are union types in TS?

In TypeScript, we can define a variable which can have multiple types of values. In other words, TypeScript can combine one or two different types of data (i.e., number, string, etc.) in a single type, which is called a union type. Union types are a powerful way to express a variable with multiple types.

What is union type variable declaration?

A "union declaration" specifies a set of variable values and, optionally, a tag naming the union. The variable values are called "members" of the union and can have different types.


1 Answers

You can index by number instead of keyof T. keyof T will contain all keys of the tuple object which includes the length as well as any other array properties.

type NeededUnionType<T extends any[]> = T[number]; // Includes all the Array properties values

const value: NeededUnionType<[7, string]> = 2; // err value is 7 | string 

Playground Link

like image 110
Titian Cernicova-Dragomir Avatar answered Nov 15 '22 22:11

Titian Cernicova-Dragomir