How to Access Dictionary Value by Key in TypeScript ?
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.
Table of Content
- Using Square Bracket Notation
- Using Dot Notation
- Using Object Methods
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.
interface Dictionary {
name: string;
desc: string;
est: number;
}
let dictionary: Dictionary = {
name: "w3wiki",
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:
w3wiki
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.
interface Dictionary {
name: string;
desc: string;
est: number;
}
let dictionary: Dictionary = {
name: "w3wiki",
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:
w3wiki
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:
interface Dictionary {
name: string;
desc: string;
est: number;
}
let dictionary: Dictionary = {
name: "w3wiki",
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"]
["w3wiki", "A Computer Science Portal", 2009]