Learn TypeScript
Using a user-defined type guard with a type predicate
Using a user-defined type guard with a type predicate
In this lesson, we will learn about a way of narrowing a type with a custom function.
Understanding a type predicate
A type predicate can be used in a function's return type to indicate the narrowed type of the parameter:
function isTypeName(paramName: WideTypeName): paramName is NarrowTypeName { // some check return boolean_result_of_check;}
paramName is NarrowTypeName
is the type predicate in the above function.
A type guard function must return a boolean value if a type predicate is used.
An example
We are going to explore a user-defined type guard with a type predicate in the code editor below:
The editor contains the same example as we used in the last lesson.
- Let's create a user defined type guard to check whether an object is a
Person
:
function isPerson(contact: Contact): contact is Person { return (contact as Person).firstName !== undefined;}
We could have used "firstName" in contact
as the return statement, but this could be used directly as a type guard. A more common implementation for a user-defined type guard is to check whether properties have values, which is what we have done here.
- In the
sayHello
function, output "Hello {firstName}" if thecontact
parameter is aPerson
using theisPerson
type guard:
function sayHello(contact: Contact) { if (isPerson(contact)) { console.log("Hello " + contact.firstName); }}
What is the type of contact
in the if
branch?
Neat!
- Create a type guard function, called
isOrganisation
, to check whether an object is anOrganisation
.
- Complete the
sayHello
function implementation by outputing "Hello {name}" if thecontact
parameter is anOrganisation
using theisOrganisation
type guard function.
What is the type of contact
in the if
branch you just implemented?
Nice!
Summary
A user-defined type guard can carry out checks on its parameter and use a type predicate to tell TypeScript its type. A user-defined type guard that uses a type predicate must return a boolean value.
In the next lesson, we will learn another method of implementing a user-defined type guard.