By utilizing Indexed Types
TypeScript’s indexed types allow us to create object types based on existing types. By leveraging indexed types, we can declare object value types without explicitly mentioning key types.
Syntax:
type MyObject = { [key in string]: ValueType };
Example: This example shows the declaration of the object value type without declaring the key type by the use of the Indexed type.
Javascript
// Approach 4: Utilizing Indexed Types in JavaScript // Utilizing Indexed Types type MyObject = { [key in string]: number }; // Create an object of type MyObject const myNumericObject: MyObject = { "age" : 30, "height" : 180, "weight" : 75, }; // Access and use the object console.log(myNumericObject[ 'age' ]); console.log(myNumericObject[ 'height' ]); console.log(myNumericObject[ 'weight' ]); |
Output:
30
180
75
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