How to use Extract Utility Type In Typescript
In this approach, we are using Extract Utility Type, where we have defined the tuple as tupVal and created a type as tupleToUnion2 by extracting a union type from its assignable values. Then we use the derived type to declare a variable myVar that can only be assigned values of the extracted union type.
Syntax:
type Extract<T, U> = T extends U ? T : never;
Example: Below is the implementation of the above-discussed approach.
const tupVal = ['Hello GFG', 23, true] as const;
type tupleToUnion2 =
Extract<typeof tupVal[number], string | number | boolean>;
const myVar: tupleToUnion2 = 23 ;
console.log(myVar);
Output:
23
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