Last Updated : 18 Jul, 2024
TypeScript Generic Object Types allow you to create flexible and reusable type definitions for objects. These generic types can work with different shapes of objects while providing type safety, ensuring your code is both robust and adaptable. They are particularly useful for creating functions or classes that can handle various object structures while maintaining type correctness.
Syntaxtype MyGenericObject<T> = { key: string; value: T; };Example 1: Key-Value Pairs
In this example, we create a generic object type to represent key-value pairs. The type parameter T represents the value type, allowing for different data types to be used.
TypeScript
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: Encapsulating Data Properties
In this example, we define a generic object type that encapsulates a data property of a specified type T. This showcases how generic object types can store and access different data types.
JavaScript
type DataContainer<T> = {
data: T;
};
const numericData: DataContainer<number> = { data: 25 };
const stringData: DataContainer<string> = { data: 'TypeScript' };
console.log(numericData.data);
console.log(stringData.data);
Output:
25 TypeScriptConclusion
TypeScript's Generic Object Types provide a powerful way to create flexible, reusable, and type-safe object definitions. By leveraging these types, you can build more robust and adaptable code, ensuring that your functions and classes can handle different object structures while maintaining strict type correctness. This approach enhances code maintainability and reduces the risk of errors, making it an essential tool in a TypeScript developer's toolkit.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4