How to use the Map object In Typescript
Similar to JavaScript, TypeScript also provides a dedicated data structure called as ‘Map‘ to store key-value pairs. It has ‘has’ method that is used to check if a specific key exists in the map. It can be used as a alternative to object-based approaches.
Syntax
if(map.has(key)){
// key exists
} else{
// key does not exist
}
Example: The below code uses the Map object to check if a key exists in dictionary in TypeScript.
let map = new Map<string, string>();
map.set('name', 'w3wiki');
map.set('desc', 'A computer science portal');
map.set('est', '2009');
let keyToCheck:string = "desc";
if (map.has(keyToCheck)) {
console.log(
`Key ${keyToCheck} exists in the dictionary.`);
} else {
console.log(
`Key ${keyToCheck} doesn't exist in the dictionary.`);
}
Output:
"Key desc exists in the dictionary."
How to Check if a Key Exists in a Dictionary in TypeScript ?
In TypeScript dictionaries are used whenever the data is needed to be stored in key and value form. We often retrieve the data from the dictionaries using an associated key. Therefore it becomes crucial to check whether the key exists in a dictionary or not.
We can use the below methods to check if a key exists or not in a dictionary.
Table of Content
- Using an ‘in’ operator
- Using the hasOwnProperty method
- Using the undefined keyword
- Using the Map object
- Using for loop