How to use Mapped Type In Typescript
In this approach, we are using Mapped Type to derive union type. We have defined the mapped type as tupleToUnion1 which converts a tuple type T into the union type of its elements. The unionFromTuple is a type that is derived from the tuple tupVal and an ex is the assigned valid value (Hello GFG) to the derived union type.
Syntax:
type TupleToUnion<T extends any[]> = T[number];
Example: Below is the implementation of the above-discussed approach.
type tupleToUnion1<T extends any[]> = T[number];
const tupVal: [string, number, boolean] = ['Hello GFG', 23, true];
type unionFromTuple = tupleToUnion1<typeof tupVal>;
const ex: unionFromTuple = 'Hello GFG';
console.log(ex);
Output:
"Hello GFG"
How to Derive Union Type From Tuple/Array Values in TypeScript ?
This article will show how to derive union type from tuple/array values in TypeScript language. The union type in TypeScript is mainly formed by combining multiple types. We will see various approaches through which we can derive union type.
Below are the possible approaches:
Table of Content
- Using Mapped Type
- Using Extract Utility Type
- Using Conditional Types with infer