Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
TypeScript Object Extending Types
Next article icon

TypeScript Generic Object Types

Last Updated : 18 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Syntax

type 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 TypeScript

Conclusion

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.


Next Article
TypeScript Object Extending Types

S

sahoopratyushkumar3
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • TypeScript
  • Geeks Premier League 2023

Similar Reads

  • TypeScript Generic Types
    TypeScript Generic Types can be used by programmers when they need to create reusable components because they are used to create components that work with various data types and this provides type safety. The reusable components can be classes, functions, and interfaces. TypeScript generics can be u
    2 min read
  • TypeScript Object Types
    TypeScript object types define the structure of objects by specifying property types, ensuring type safety and clarity when passing objects as function parameters. Optional properties, denoted with a ? provide flexibility for objects with varying properties. This approach enhances code robustness by
    3 min read
  • TypeScript Object Extending Types
    TypeScript Object Extending Types refers to the ability to create new object types or interfaces that inherit properties and methods from existing ones using the extends keyword. This allows developers to build more complex, reusable, and maintainable type definitions by composing simpler types. Syn
    3 min read
  • TypeScript Object Intersection Types
    In TypeScript, Object Intersection Types are a way to create new types by combining multiple types into a single type. This is done using the & (ampersand) operator. Intersection types allow you to express that an object must have all the properties and methods of each type in the intersection.
    3 min read
  • Typescript Generic Type Array
    A generic type array is an array that is defined using the generic type in TypeScript. A generic type can be defined between the angled brackets(<>). Syntax:// Syntax for generic type arraylet myArray: Array<Type>;Example 1: Creating a simple generic type array of number type in Typescri
    1 min read
  • TypeScript Object Tuple Types
    TypeScript provides various features to enhance type safety and developer productivity. One of these features includes Object Tuple Types. This feature ensures that an object follows a consistent shape in our code which results in a reduction in runtime errors and improves code quality. What are Obj
    5 min read
  • Higher-Order Types in TypeScript
    Higher-order types are among the advanced aspects of Typescript that give priority to types as first-class citizens, similar to higher-order functions of JavaScript that accept a function as an argument or return a function, higher-order types can accept types or return types. These are the followin
    6 min read
  • TypeScript Object The Array Type
    In TypeScript, the Array Type is used to specify and enforce the type of elements that can be stored in an array, enhancing type safety during development. This adaptability ensures reusability across diverse data types, as exemplified by the Array type (e.g., number[] or string[]). Syntaxlet myArra
    2 min read
  • TypeScript Interfaces Type
    TypeScript Interfaces Type offers an alternative method for defining an object's type, allowing for a distinct naming approach. Syntax:interface InterfaceName { property1: type1; property2?: type2; readonly property3: type3; // ... method1(): returnType1; method2(): returnType2; // ...}Parameters:in
    2 min read
  • Opaque Types In TypeScript
    In TypeScript Opaque types concept allows for the definition of specialized types such as strings or numbers which are derived from primitive types but do not have the characteristics of the base types, the purpose of this is to prevent specific actions regarding the type in question, or to make thi
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences