How to use Conditional Types with infer In Typescript
In this approach, we utilize conditional types with the infer keyword to extract individual types from the tuple/array and then merge them into a union type.
Syntax:
type TupleToUnion3<T extends readonly any[]> = T extends readonly (infer U)[] ? U : never;
Example: This TypeScript snippet derives a union type from a tuple/array using conditional types with `infer`. It extracts the individual types from the tuple and forms a union.
type TupleToUnion3<T extends readonly any[]> =
T extends readonly (infer U)[] ? U : never;
const tupVal = ['Hello GFG', 23, true] as const;
type UnionFromTuple2 = TupleToUnion3<typeof tupVal>;
const ex2: UnionFromTuple2 = true;
console.log(ex2);
Output:
true
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