The in and keyof Operators
Explore how to apply the in operator to create type guards distinguishing between different interfaces and use the keyof keyword to extract property names as string literal types. This lesson enables you to write safer and more maintainable TypeScript code when working with interfaces.
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...