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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With