How to use the undefined keyword In Typescript

We know that the JavaScript objects returns an undefined if a key does not exist. Being a superset of JavaScript, TypeScript also returns an undefined if a key does not exist. Therefore, we can perform a simple check for undefined to determine the existence of a key in a dictionary in TypeScript.

Syntax

if(dictionary[key] !== undefined){
// Key exists
} else{
// Key does not exist
}

Example: The below code uses the ‘undefined’ keyword to check if a key exists in dictionary in TypeScript.

Javascript
interface Dictionary{
    [key:string]:string;
}
let dictionary:Dictionary = {
    "name": "w3wiki",
    "desc": "A computer science portal",
    "est": "2009" };
let keyToCheck:string = "subjects";

if (dictionary[keyToCheck] !== undefined) {
    console.log(
        `Key ${keyToCheck} exists in the dictionary.`);
} else {
    console.log(
        `Key ${keyToCheck} doesn't exist in the dictionary.`);
}


Output:

"Key subjects 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

Similar Reads

1. Using an ‘in’ operator

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

2. Using the hasOwnProperty method

The ‘hasOwnProperty’ method is a TypeScript built-in method that we use to check if an object has a property with a specific key. It returns a boolean value and is used when we want to explicitly check for the existence of a property....

3. Using the undefined keyword

We know that the JavaScript objects returns an undefined if a key does not exist. Being a superset of JavaScript, TypeScript also returns an undefined if a key does not exist. Therefore, we can perform a simple check for undefined to determine the existence of a key in a dictionary in TypeScript....

4. Using the Map object

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

5. Using for loop

In this approach we iterate over the keys of the dictionary using for loop and compare each key with the key we searching for....

Contact Us