Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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 Types
Next article icon

TypeScript Object Types

Last Updated : 23 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 allowing the omission of certain properties when appropriate.
JavaScript
interface Person {     name: string;     age: number;     address?: string; // Optional property }  function greet(person: Person): string {     return `Hello, ${person.name}!`; }  const user: Person = {     name: "Alice",     age: 30 };  console.log(greet(user));  
  • The Person interface defines an object type with name and age as required properties, and address as an optional property.
  • The greet function accepts a parameter of type Person and returns a greeting message.
  • The user object adheres to the Person interface, and the greet function is called with this object.

Output:

Hello, Alice!

More Example of TypeScript Object Types

Defining a Car Object

JavaScript
interface Car {     make: string;     model: string;     year: number;     electric?: boolean; // Optional property }  const myCar: Car = {     make: "Tesla",     model: "Model S",     year: 2022,     electric: true };  console.log(`I drive a ${myCar.year} ${myCar.make} ${myCar.model}.`); 
  • The Car interface defines an object type with make, model, and year as required properties, and electric as an optional property.
  • The myCar object adheres to the Car interface, specifying values for all properties.

Output:

I drive a 2022 Tesla Model S.

Nested Object Types for a Book

JavaScript
interface Author {     name: string;     birthYear: number; }  interface Book {     title: string;     author: Author;     pages: number;     genre?: string; // Optional property }  const myBook: Book = {     title: "TypeScript Basics",     author: {         name: "Jane Doe",         birthYear: 1980     },     pages: 350 };  console.log(`${myBook.title} by ${myBook.author.name}`); 
  • The Author interface defines the structure for an author object.
  • The Book interface includes a nested author property of type Author, along with other properties.
  • The myBook object conforms to the Book interface, including a nested author object.

Output:

TypeScript Basics by Jane Doe

Function Parameter with Object Type

JavaScript
interface Rectangle {     width: number;     height: number; } function calculateArea(rect: Rectangle): number {     return rect.width * rect.height; } const myRectangle: Rectangle = {     width: 10,     height: 5 }; console.log(`Area: ${calculateArea(myRectangle)}`); 
  • The Rectangle interface defines the structure for a rectangle object.
  • The calculateArea function accepts a parameter of type Rectangle and returns the area.
  • The myRectangle object adheres to the Rectangle interface and is passed to the function.

Output:

Area: 50

Best Practices for Using TypeScript Object Types

  • Prefer Interfaces for Object Type Definitions: Use interface to define object shapes, as they are extendable and provide clear intent.
  • Utilize Type Aliases for Complex Types: Employ type aliases when defining complex types, such as unions or intersections, to enhance code readability.
  • Leverage Readonly Properties: Mark properties as readonly to prevent unintended mutations, ensuring data integrity.
  • Avoid Excessive Typing: Rely on TypeScript's type inference where possible to reduce redundancy and maintain cleaner code.

Next Article
TypeScript Object Types

N

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

Similar Reads

    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
    TypeScript Object
    A TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data.What Are TypeScript Objects?An object
    5 min read
    TypeScript Generic Object Types
    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 c
    3 min read
    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 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
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