How to use Square Bracket Notation In Typescript
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
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