Type Checking an Interface with Custom User-Defined Type Guard

This lesson shows a way to type check by manually building an algorithm that aims to find unique characteristics in the structure.

User-defined function

A custom user-defined type guard is a function that checks specific parts of the structure of an object to determine if it is one type or another. The advantage is that the type does not need to be altered with a branded property or used with a discriminator. However, it comes with the cost of foregoing functions that check every type.

The following code has a function on line 21 which takes a single parameter of type any. The function checks for two members and because any is used, it can be anything. When the function returns true, the function will help TypeScript to narrow the type to the one defined after is. On line 21, the function narrows to Person.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy