How to useMapped Types in Typescript

By changing existing types, mapped types make it possible to create new ones. We can create a type with certain value types while keeping the keys accessible by utilizing mapped types.

Syntax:

type MyObject = { [key: string]: ValueType };

Example: This example shows the declaration of the object value type without declaring the key type by the use of the mapped type.

Javascript




// Approach 2: Leveraging Mapped Types in JavaScript
 
// Indexed type with string keys
type StringIndexedType = {
    // Value type for string keys
    [key: string]: number;
};
 
// Indexed type with number keys
type NumberIndexedType = {
    // Value type for number keys
    [key: number]: string;
};
 
// Example usage
const stringIndexedObject: StringIndexedType = {
    "key1": 10,
    "key2": 20,
};
 
const numberIndexedObject: NumberIndexedType = {
    1: "value1",
    2: "value2",
};
 
// Output using console.log
console.log(stringIndexedObject["key1"]);
console.log(numberIndexedObject[1]);


Output:

10
value1

How to Declare Object Value Type Without Declaring Key Type in TypeScript ?

We will create an object value type without declaring the key type. We can not directly define the type of value we will use different methods for declaring the object value type.

These are the following methods for declaring the object value type:

Table of Content

  • Using Record Utility Type
  • Using Mapped Types
  • Using Generics
  • By utilizing Indexed Types

Similar Reads

Approach 1: Using Record Utility Type

The Record utility type is used to define an object type in TypeScript with specific keys and a common value type. It allows you to create a type that represents an object with known keys and a shared type for all values....

Approach 2: Using Mapped Types

...

Approach 3: Using Generics

By changing existing types, mapped types make it possible to create new ones. We can create a type with certain value types while keeping the keys accessible by utilizing mapped types....

Approach 4: By utilizing Indexed Types

...

Contact Us