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:
Here, we have two interfaces:
- The first is
IIdName, and contains anidproperty of typenumberand anameproperty of typestring. - The second interface is
IDescrValue, and contains adescrproperty of typestring, and avalueproperty 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:
-
We have a function named
printNameOrValuefrom lines 13–22 that has a single parameter namedobj, which can either be of the typeIIdName, or of the typeIDescrValue...