How to useGenerics in Typescript
Generics provide a flexible way to write functions and classes by allowing types to be specified later. We can use generics to define the value type while keeping the key type generic.
Syntax:
type MyObject<T> = { [key: string]: T };
Example: This example shows the declaration of the object value type without declaring the key type by the use of the Generics.
Javascript
// Approach 3: Employing Generics in JavaScript type MyObject<T> = { [key: string]: T }; // Create an object of type // MyObject with number values const numberObject: MyObject<number> = { key1: 10, key2: 20, key3: 30, }; // Create an object of type // MyObject with string values const stringObject: MyObject<string> = { name: "John" , city: "New York" , country: "USA" , }; // Access and use the objects console.log(numberObject[ 'key2' ]); console.log(stringObject[ 'city' ]); |
Output:
20
New York
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
Contact Us