How to use the "in" operator in TypeScript



Image not found!!

In TypeScript, the in operator is used to check if a property exists in an object or if an index exists in an array. Here's how you can use it:

Checking for a property in an object:

typescript
interface MyObject { name: string; age: number; } const myObject: MyObject = { name: 'John', age: 25, }; if ('name' in myObject) { console.log('Property "name" exists in myObject.'); } else { console.log('Property "name" does not exist in myObject.'); }

Checking for an index in an array:

typescript
const myArray: string[] = ['apple', 'banana', 'orange']; if (1 in myArray) { console.log('Index 1 exists in myArray.'); } else { console.log('Index 1 does not exist in myArray.'); }

In the array example, the in operator checks if the index 1 exists in the array myArray. If the index exists, it will execute the code inside the if block; otherwise, it will execute the code inside the else block.

Using the in operator is a type-safe way to check for the existence of properties or indices, and TypeScript will provide appropriate type checking and autocompletion based on the type of the object or array.