Create Objects with Dynamic Keys Using Index Signature

In this approach, we are using an index signature with the interface dict to create an object where keys are dynamically typed strings, allowing for properties like ‘title,’ ‘category,’ ‘likes,’ and ‘foundedYear‘ with values of either strings or numbers.

Syntax:

{
[keyType: KeyType]: ValueType;
}

Example: The below example uses Index Signature to Create Objects with Dynamic Keys in TypeScript.

Javascript
interface dict {
    [key: string]: string | number;
}
const obj: dict = {
    title: 'w3wiki',
    category: 'Computer Science',
    likes: 10000,
    foundedYear: 2008,
};

console.log(obj);

Output:

{
"title": "w3wiki",
"category": "Computer Science",
"likes": 10000,
"foundedYear": 2008
}

How to Create Objects with Dynamic Keys in TypeScript ?

In TypeScript, we can create objects with Dynamic Keys by providing the index signature syntax. We can define the index signature, that allows objects to have keys with specific types. We can also use the Record Utility to create objects with Dynamic Keys.

These are the following approaches:

Table of Content

  • Using Index Signature
  • Using Record Type

Similar Reads

Create Objects with Dynamic Keys Using Index Signature

In this approach, we are using an index signature with the interface dict to create an object where keys are dynamically typed strings, allowing for properties like ‘title,’ ‘category,’ ‘likes,’ and ‘foundedYear‘ with values of either strings or numbers....

Create Objects with Dynamic Keys Using Record Type

In this approach, we are using the Record type with a dynamic string key type (keys) to create an object (obj) where keys can be any string, providing flexibility for properties like ‘title,’ ‘category,’ ‘likes,’ ‘foundedYear,’ and ‘founder‘ with values of either strings or numbers....

Using Mapped Types

Mapped types in TypeScript allow us to create new types by transforming the properties of an existing type. We can leverage mapped types to dynamically generate object types with specific keys and value types....