Open In App

How to Access Dictionary Value by Key in TypeScript ?

Last Updated : 12 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 by key.

Using Square Bracket Notation

It is the most common way to access the dictionary value. Here we use square brackets ([]) to access the value associated with a key. If the accessed key does not exist in the dictionary, TypeScript returns an “undefined” instead of raising an error.

Syntax:

let value = dictionary[key];

Example: The below code uses the square bracket notation to access the dictionary value by key in TypeScript.

Javascript
interface Dictionary {
    name: string;
    desc: string;
    est: number;
}

let dictionary: Dictionary = {
    name: "GeeksforGeeks",
    desc: "A Computer Science Portal",
    est: 2009
};

let value1: string = dictionary["name"];
let value2: string = dictionary["desc"];
let value3: number = dictionary["est"];

console.log(value1);
console.log(value2);
console.log(value3);

Output:

GeeksforGeeks
A Computer Science Portal
2009

Using Dot Notation

It’s another way to access the dictionary value. Here instead of using the brackets to pass the search key, we use a dot followed by the key name. This method also returns an “undefined” if the key does not exist.

Syntax:

let value = dictionary.key

Example: The below code uses the dot notation to access the dictionary value by key in TypeScript.

Javascript
interface Dictionary {
    name: string;
    desc: string;
    est: number;
}

let dictionary: Dictionary = {
    name: "GeeksforGeeks",
    desc: "A Computer Science Portal",
    est: 2009
};

let value1: string = dictionary.name;
let value2: string = dictionary.desc;
let value3: number = dictionary.est;

console.log(value1);
console.log(value2);
console.log(value3);

Output:

GeeksforGeeks
A Computer Science Portal
2009

Using Object Methods

TypeScript provides Object methods like Object.keys() and Object.values() which can be used to access dictionary values by key.

Syntax:

let keys = Object.keys(dictionary);
let values = Object.values(dictionary);

Example:

JavaScript
interface Dictionary {
    name: string;
    desc: string;
    est: number;
}

let dictionary: Dictionary = {
    name: "GeeksforGeeks",
    desc: "A Computer Science Portal",
    est: 2009
};

let keys = Object.keys(dictionary);
let values = Object.values(dictionary);

console.log(keys);   
console.log(values);

Output:

["name", "desc", "est"]
["GeeksforGeeks", "A Computer Science Portal", 2009]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads