How to Create Objects with Dynamic Keys in TypeScript ?
Last Updated :
08 Aug, 2024
In TypeScript, objects with dynamic keys are those where the key names are not fixed and can be dynamically determined at runtime. This allows the creation of flexible data structures where properties can be added or accessed using variables, providing more versatile type definitions.
These are the following approaches:
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: 'GeeksforGeeks',
category: 'Computer Science',
likes: 10000,
foundedYear: 2008,
};
console.log(obj);
Output:
{
"title": "GeeksforGeeks",
"category": "Computer Science",
"likes": 10000,
"foundedYear": 2008
}
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.
Syntax:
Record<Keys, Type>
Example: The below example uses Record Type to Create Objects with Dynamic Keys in TypeScript.
JavaScript
type keys = string;
const obj: Record<keys, string | number> = {
title: 'GeeksforGeeks',
category: 'Computer Science',
likes: 10000,
foundedYear: 2008,
founder: "Sandeep Jain",
};
console.log(obj);
Output:
{
"title": "GeeksforGeeks",
"category": "Computer Science",
"likes": 10000,
"foundedYear": 2008,
"founder": "Sandeep Jain"
}
Create Objects with Dynamic Keys 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.
Syntax:
type DynamicObject<KeyType extends string | number, ValueType> = {
[K in KeyType]: ValueType;
};
Example: The following example demonstrates how to use a mapped type to create objects with dynamic keys in TypeScript.
JavaScript
type DynamicObject<KeyType extends string | number, ValueType> = {
[K in KeyType]: ValueType;
};
const obj: DynamicObject<"title" | "category" | "likes" | "foundedYear",
string | number> = {
title: 'GeeksforGeeks',
category: 'Computer Science',
likes: 10000,
foundedYear: 2008,
};
console.log(obj);
Output:
{
"title": "GeeksforGeeks",
"category": "Computer Science",
"likes": 10000,
"foundedYear": 2008
}
Each of these methods provides a flexible way to handle objects with dynamic keys in TypeScript, allowing for a variety of use cases depending on your requirements.
Similar Reads
How to Create a Typed Array from an Object with Keys in TypeScript?
Creating a typed array from the keys of an object in TypeScript ensures that your application maintains type safety, particularly when interacting with object properties. Here we'll explore different approaches to achieve this using TypeScript's built-in Object methods. Below are the approaches used
3 min read
How to Create an Observable with a Delay in TypeScript ?
Creating observables with delays is a common requirement in TypeScript applications, especially when dealing with asynchronous operations. To achieve this, we leverage the power of the rxjs library. What is rxjs library?The RxJS library is a powerful reactive programming library for JavaScript and T
3 min read
How to Get an Object Value By Key in TypeScript
In TypeScript, we can get an object value by key by accessing the specific properties within the objects of the dynamic type. This can be done using Dot Notation, Bracket Notation, and Optional Chaining. In this article, we will explore all these approaches along with their implementation in terms o
5 min read
How to Define Strongly Type Nested Object Keys with Generics in TypeScript ?
We will look into the effective use of generics in TypeScript to ensure type safety when working with nested objects. By employing generics, developers can establish strongly typed keys for nested objects, significantly reducing the likelihood of runtime errors and enhancing code maintainability. Ta
2 min read
How to Create an Enum With String Values in TypeScript ?
To create an enum with string values in TypesScript, we have different approaches. In this article, we are going to learn how to create an enum with string values in TypesScript. Below are the approaches used to create an enum with string values in TypesScript: Table of Content Approach 1: Using Enu
3 min read
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 TypeUsing Map
4 min read
How to Initialize a TypeScript Object with a JSON-Object ?
To initialize a TypeScript Object with a JSON-Object, we have multiple approaches. In this article, we are going to learn how to initialize a TypeScript Object with a JSON-Object. Below are the approaches used to initialize a TypeScript Object with a JSON-Object: Table of Content Object.assign Type
3 min read
How to Create Dynamic Values and Objects in JavaScript?
In JavaScript, you can choose dynamic values or variable names and object names and choose to edit the variable name in the future without accessing the array, Dynamic values and objects in JavaScript allow changing, accessing, or creating values and object properties at runtime for flexibility and
3 min read
How to set state with a dynamic key name in ReactJS ?
When working with ReactJS, managing state is a fundamental aspect of building dynamic and interactive user interfaces. In some cases, you may encounter situations where you need to set a state with a dynamic key name, rather than a fixed one. This can be particularly useful when dealing with dynamic
2 min read
How to Sort or Reduce an Object by Key in TypeScript ?
Sorting an object by key generally refers to arranging its properties in a specific order, while reducing involves selecting a subset of properties based on provided keys. Different approaches allow developers to perform these operations with flexibility. Below are the approaches used to sort or red
3 min read