Learn TypeScript
Using an `in` type guard
Using an `in` type guard
In this lesson, we will learn about the in operator and how it can narrow the type of object structures.
Understanding the in operator
in is a JavaScript operator that can be used to check whether a property belongs to a particular object.
The syntax is:
propertyName in objectVariable;The expression returns true or false depending on whether the property belongs to the object.
The TypeScript compiler uses an in expression to narrow the variable's type in the expression.
An example
We are going to explore the in type guard in the code editor below:
The editor contains code similar to the last lesson's example, but interfaces are used for the object structures rather than classes.
- In the function, output "Hello {firstName}" if the
contactparameter contains afirstNameproperty:
function sayHello(contact: Contact) { if ("firstName" in contact) { console.log("Hello " + contact.firstName); }}What is the type of contact in the if branch?
- Complete the function implementation by outputing "Hello {name}" if the
contactparameter contains anameproperty.
What is the type of contact in the if branch you just implemented?
Nice!
Summary
The in operator can be used to help TypeScript narrow the type of an object variable by its property name. It is arguably more useful than instanceof because it can be applied to any object structure.
Next up, we will learn about user-defined type guards.
