...

/

The in and keyof Operators

The in and keyof Operators

Learn how to use the in operator and type guards in TypeScript to distinguish between object interfaces, along with extracting property names using the keyof operator.

The in operator

JavaScript and, subsequently, TypeScript allow us to interrogate an object and see if it has a property using the in operator.

Let’s explore this operator with the following interfaces:

// Define the IIdName interface
interface IIdName {
id: number;
name: string;
}
// Define the IDescrValue interface
interface IDescrValue {
descr: string;
value: number;
}
TypeScript interfaces

Here, we have two interfaces:

  • The first is IIdName, and contains an id property of type number and a name property of type string.
  • The second interface is IDescrValue, and contains a descr property of type string, and a value property of type number.

Note that these interfaces describe completely different objects and have no overlapping properties whatsoever.

Using the in operator in a function

We can now write a function that will distinguish between these two interfaces using the in operator as follows:

interface IIdName {
id: number;
name: string;
}
interface IDescrValue {
descr: string;
value: number;
}
// Define the printNameOrValue function which takes an object
// that implements either the IIdName or IDescrValue interface
function printNameOrValue(obj: IIdName | IDescrValue): void {
// Use the 'in' operator to check if the object has an 'id' property
if ('id' in obj) {
console.log(`obj.name : ${obj.name}`);
}
// Use the 'in' operator to check if the object has a 'descr' property
if ('descr' in obj) {
console.log(`obj.value : ${obj.value}`);
}
}
Using the in operator with interfaces
  • We have a function named printNameOrValue from lines 13–22 that has a single parameter named obj, which can either be of the type IIdName, or of the type IDescrValue. ...