How to use Mapped Types In Typescript
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.
type DynamicObject<KeyType extends string | number, ValueType> = {
[K in KeyType]: ValueType;
};
const obj: DynamicObject<"title" | "category" | "likes" | "foundedYear", string | number> = {
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