How to use an ‘in’ operator In Typescript
The ‘in’ operator checks whether a specific key or a property exists in an object or not. It is a widely used approach as it provides a simplistic way to check the existence of a key in TypeScript dictionaries.
Syntax:
if(key in dictionary){
// key exists
} else{
// key does not exist
}
Example: The below code uses the ‘in’ operator to check if a key exists in a dictionary in TypeScript.
interface Dictionary{
[key:string]:string;
}
let dictionary:Dictionary = {
"name": "w3wiki",
"desc": "A computer science portal",
"est": "2009" };
let keyToCheck:string = "other";
if (keyToCheck in dictionary) {
console.log(
`Key ${keyToCheck} exists in the dictionary.`);
} else {
console.log(
`Key ${keyToCheck} doesn't exist in the dictionary.`);
}
Output:
"Key other doesn't exist 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