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:
How to Access Dictionary Value by Key in TypeScript ?
Next article icon

How to Get an Object Value By Key in TypeScript

Last Updated : 28 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In TypeScript, we can get an object value by key by accessing the specific properties within the objects of the dynamic type. This can be done using Dot Notation, Bracket Notation, and Optional Chaining. In this article, we will explore all these approaches along with their implementation in terms of examples and outputs.

Table of Content

  • Using Dot Notation
  • Using Bracket Notation
  • Using Optional Chaining
  • Using Object.hasOwnProperty() Method
  • Using Object.entries() and Array.find()
  • Using Object.keys() Method
  • Using TypeScript's in Operator
  • Using TypeScript’s Record Utility Type

Using Dot Notation

Dot notation is used in TypeScript to directly access the value associated with the "name" key within the object obj. The result is stored in the variable res, which consists of the value "GeeksforGeeks," and is then printed to the console.

Syntax:

let value = obj.key

Example: The below example uses Dot Notation to Get an Object Value By Key in TypeScript.

JavaScript
const obj: { [key: string]: string } = {     name: "GeeksforGeeks",     category: "Programming",     language: "TypeScript", }; const res: string = obj.name; console.log(res); 

Output:

"GeeksforGeeks" 

Using Bracket Notation

In this approach, we are using bracket notation ([]) in TypeScript to access the value associated with the "category" key within the object obj. The result is stored in the variable res, which consists of the value "Programming," and is then printed to the console.

Syntax:

let value = obj[key];

Example: The below example uses Bracket Notation to Get an Object Value By Key in TypeScript.

JavaScript
const obj: { [key: string]: string } = {     name: "GeeksforGeeks",     category: "Programming",     language: "TypeScript", }; const res: string = obj['category']; console.log(res); 

Output:

"Programming" 

Using Optional Chaining

In this approach, we are using optional chaining in TypeScript, we access the value associated with the "language" key within the object obj. The result, is then converted to uppercase which is stored in the variable res, which contains "TYPESCRIPT" and is then printed to the console.

Syntax:

object?.property
object?.method()
object?.[expression]

Example: The below example uses Optional Chaining to Get an Object Value By Key in TypeScript.

JavaScript
const obj: { name?: string; category?: string; language?: string } = {     name: "GeeksforGeeks",     category: "Programming",     language: "TypeScript", }; const res: string | undefined = obj.language?.toUpperCase(); console.log(res); 

Output:

"TYPESCRIPT" 

Using Object.hasOwnProperty() Method

This method checks if an object contains a specified property as its own property, and if it does, retrieves the corresponding value. It's particularly useful when you want to ensure that the property exists before accessing its value.

Syntax:

if (obj.hasOwnProperty(key)) {
let value = obj[key];
}

Example: In this example we retrieves the value associated with the key 'category' from the object obj and logs it to the console.

JavaScript
const obj: { [key: string]: string } = {     name: "GeeksforGeeks",     category: "Programming",     language: "TypeScript", };  if (obj.hasOwnProperty('category')) {     const res: string = obj['category'];     console.log(res); } 

Output:

Programming

Using Object.entries() and Array.find()

In TypeScript, you can use Object.entries() to get an array of key-value pairs from an object. Then, you can use array methods like Array.find() to find the value associated with a specific key.

Example: In this example, we'll use Object.entries() and Array.find() to get the value associated with the key "category" from the object obj.

JavaScript
const obj: { [key: string]: string } = {     name: "GeeksforGeeks",     category: "Programming",     language: "TypeScript", };  const desiredKey = "category"; const value = Object.entries(obj).find(([key, val]) => key === desiredKey)?.[1]; console.log(value); // Logs "Programming" 

Output

Programming

Using Object.keys() Method

In TypeScript, you can use the Object.keys() method to get an array of the object's own enumerable property names. Then, you can iterate over this array to find and access the value associated with a specific key.

Syntax:

Object.keys(obj).forEach(key => {
if (key === specificKey) {
let value = obj[key];
}
});

Example: In this example, we'll use Object.keys() to get the value associated with the key "category" from the object obj.

JavaScript
let obj = { name: "GeeksforGeeks", category: "Programming", language: "TypeScript" }; let specificKey = "category"; let res: string | undefined;  Object.keys(obj).forEach(key => {     if (key === specificKey) {         res = obj[key];     } }); console.log(res); 

Output:

Programming

Using TypeScript's in Operator

Another approach to access an object value by key in TypeScript is by using the in operator. This method checks if a property exists within the object before accessing its value. It's particularly useful for ensuring that the property exists and can handle dynamic keys effectively.

Example: In this example, we use the in operator to check if the key exists in the object and then access its value.

JavaScript
interface MyObject {     name?: string;     category?: string;     language?: string; }  const obj: MyObject = {     name: "GeeksforGeeks",     category: "Programming",     language: "TypeScript" };  const key = "category"; let value: string | undefined;  if (key in obj) {     value = obj[key as keyof MyObject]; }  console.log(value); 

Output:

Programming

Using TypeScript’s Record Utility Type

TypeScript’s Record utility type allows you to define an object type with specific keys and their corresponding value types. This approach ensures that the keys are consistent and the types are correctly enforced, making it easier to access object values by their keys.

Syntax:

type Record<K extends keyof any, T> = {
[P in K]: T;
};

Example: The following example demonstrates how to define an object using the Record utility type and access its value by a specific key.

JavaScript
const obj: Record<'name' | 'category' | 'language', string> = {     name: "GeeksforGeeks",     category: "Programming",     language: "TypeScript" }; const key: keyof typeof obj = 'language'; const value: string = obj[key]; console.log(value); 

Output
TypeScript 

Next Article
How to Access Dictionary Value by Key in TypeScript ?

G

gauravgandal
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • TypeScript

Similar Reads

  • How to Create an Object in TypeScript?
    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. Creating Objects in TypescriptNow, let
    4 min read
  • How to Get Value of Input in TypeScript ?
    In TypeScript, retrieving the value of an input element is a common task when building web applications. Whether you're handling form submissions, validating user input, or manipulating data based on user interactions, accessing input values is essential. The below approaches can be utilized to get
    2 min read
  • How to Sort a Dictionary by Value in TypeScript ?
    In TypeScript, dictionaries are objects that store key-value pairs. Sorting a dictionary by value involves arranging the key-value pairs based on the values in ascending or descending order. The below approaches can be used to accomplish this task: Table of Content Using Object.entries() and Array.s
    2 min read
  • How to Access Dictionary Value by Key in TypeScript ?
    Dictionaries are often represented as the objects where keys are associated with the specific values. These TypeScript dictionaries are very similar to JavaScript objects and are used wherever data needs to be stored in key and value form. You can use the below method to access the dictionary values
    2 min read
  • How to Sort or Reduce an Object by Key in TypeScript ?
    Sorting an object by key generally refers to arranging its properties in a specific order, while reducing involves selecting a subset of properties based on provided keys. Different approaches allow developers to perform these operations with flexibility. Below are the approaches used to sort or red
    3 min read
  • TypeScript Array Object.values() Method
    Object.values() is a functionality in TypeScript that returns an array extracting the values of an object. The order of elements is the same as they are in the object. It returns an array of an object's enumerable property values. Syntax:Object.values(object);Parameters:object: Here you have to pass
    2 min read
  • How to Get a Variable Type in TypeScript
    Understanding how to effectively ascertain the type of a variable in TypeScript is important for maintaining type safety and ensuring code robustness. In this article, we'll explore various approaches to determine the type of a variable, ranging from basic JavaScript operators to TypeScript-specific
    2 min read
  • How to Check if an Object is Empty in TypeScript ?
    In TypeScript, it's common to encounter scenarios where you need to determine if an object is empty or not. An empty object typically means it contains no properties or all its properties are either undefined or null. Below are the methods to check if an object is empty or not in TypeScript: Table o
    3 min read
  • How to Convert a Bool to String Value in TypeScript ?
    When we talk about converting a boolean to a string value in TypeScript, we mean changing the data type of a variable from a boolean (true or false) to a string (a sequence of characters). We have multiple approaches to convert a bool to a string value in TypeScript. Example: let's say you have a va
    4 min read
  • How to get Value from a Dictionary in Typescript ?
    In TypeScript, a dictionary consists of objects that store data in the key-value pairs, and allow retrieval of values based on the specified keys. We can get value from a dictionary for the specific keys using various approaches. Table of Content Using Dot NotationUsing Bracket NotationUsing a Funct
    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