![]() |
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 TypeThe Record utility type is used to define an object type in TypeScript with specific keys and a common value type. It allows you to create a type that represents an object with known keys and a shared type for all values. Syntax:type MyObject = Record<string, ValueType>; Example: This example shows the declaration of the object value type without declaring the key type by the use of the record utility type.
Output: value1 Using Mapped TypesBy changing existing types, mapped types make it possible to create new ones. We can create a type with certain value types while keeping the keys accessible by utilizing mapped types. Syntax:type MyObject = { [key: string]: ValueType }; Example: This example shows the declaration of the object value type without declaring the key type by the use of the mapped type.
Output: 10 Using GenericsGenerics 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.
Output: 20 By utilizing Indexed TypesTypeScript’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.
Output: 30 Using Partial and Required Utility TypesThe Partial and Required utility types allow for manipulation of the requiredness of properties in an object type, providing flexibility in object value type declarations. Syntax:type MyPartialObject = Partial<{ [key: string]: ValueType }>; Example:
Output: 10 |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |