Mapped Types
Mapped types in TypeScript allow for creating new types by transforming the properties of existing types. We can leverage mapped types to enforce type constraints and perform type inference on tuples. Let’s see how we can use mapped types for this purpose.
Syntax:
type EnforceTuple<T> = {
[K in keyof T]: K extends number ? T[K] : never;
};
Example: To infer the first element of a tuple as tuple type using mapped type.
// Define a mapped type to enforce tuple type
type EnforceTuple<T> = {
[K in keyof T]: K extends number ? T[K] : never;
};
// Test the mapped type
type MyTuple = EnforceTuple<[number, string, boolean]>;
// MyTuple should be [number, string, boolean]
const myTuple: MyTuple = [10, 'hello', true];
console.log(myTuple);
Output:
[10, "hello", true]
How to Infer First Element of a Tuple as a Tuple Type ?
Tuples can be represented as arrays or objects in TypeScript. This will be achieved by knowing Typescript’s type system and methods such as manual inference as well as the use of the advanced type system of TypeScript.
Defining a tuple type in TypeScript resembles the array syntax with the possibility to specify the type for each element position.
Table of Content
- Using TypeScript native tuple support
- Conditional type using infer
- Mapped Types
- Manual Inference to Extract First Element as Tuple Type