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 interfaceinterface IIdName {id: number;name: string;}// Define the IDescrValue interfaceinterface IDescrValue {descr: string;value: number;}
Here, we have two interfaces:
- The first is
IIdName
, and contains anid
property of typenumber
and aname
property of typestring
. - The second interface is
IDescrValue
, and contains adescr
property of typestring
, and avalue
property of typenumber
.
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 interfacefunction printNameOrValue(obj: IIdName | IDescrValue): void {// Use the 'in' operator to check if the object has an 'id' propertyif ('id' in obj) {console.log(`obj.name : ${obj.name}`);}// Use the 'in' operator to check if the object has a 'descr' propertyif ('descr' in obj) {console.log(`obj.value : ${obj.value}`);}}
-
We have a function named
printNameOrValue
from lines 13–22 that has a single parameter namedobj
, which can either be of the typeIIdName
, or of the typeIDescrValue
. ...