Open In App

TypeScript Generic Object Types

TypeScript Generic Object Types allow you to create flexible and reusable type definitions for objects. Generic object types can work with different shapes of objects while providing type safety. They are particularly useful when you want to create functions or classes that can work with a variety of object structures while ensuring type correctness.

Syntax:

type MyGenericObject<T> = {
key: string;
value: T;
};

Example 1: In this example, we’ll create a generic object type to represent key-value pairs. The type parameter T represents the value type.






type KeyValuePair<T> = {
    key: string;
    value: T;
};
 
const stringPair: KeyValuePair<string> =
    { key: "name", value: "John" };
const numberPair: KeyValuePair<number> =
    { key: "age", value: 30 };
 
console.log(stringPair);
console.log(numberPair);

Output :

{ key: 'name', value: 'John' }
{ key: 'age', value: 30 }

Example 2: In this example, we’ll define a generic object type that encapsulates a data property of a specified type (T) and creates instances holding numeric and string data, showcasing how generic object types can store and access different data types.






type MyGenericObject<T> = {
    data: T;
};
 
const number_Obj: MyGenericObject<number> =
    { data: 25 };
const string_Obj: MyGenericObject<string> =
    { data: "TypeScript" };
 
console.log(number_Obj.data);
console.log(string_Obj.data);

Output:

25
TypeScript
Article Tags :