Learn TypeScript

Using a `typeof` type guard

Using a `typeof` type guard

A type guard is a mechanism of narrowing a type. There are several types of type guards in TypeScript, and we will learn about the typeof method in this lesson.

Understanding the typeof type guard

We are going to explore the typeof type guard in the code editor below:

TypeScriptOpen exercise in CodeSandbox

The code contains the start of a function implementation. The function takes in a parameter that is a string or a number.

  • Add the following code to the function:
function double(item: string | number) {
if (typeof item === "string") {
return item.concat(item);
} else {
return item + item;
}
}

typeof is a JavaScript operator that returns a string indicating the JavaScript type of the operand.

🤔

What is the type of item in the if branch?

🤔

What is the type of item in the else branch?

So, TypeScript has cleverly narrowed the type of item in the branches of logic following the typeof check. This is called a typeof type guard and is useful on variables or expressions with primitive types.

Summary

TypeScript can narrow the type of a variable following an if statement that uses a typeof check. This approach is useful when checking against primitive types.

In the next lesson, we will learn about a type guard that is helpful for classes.

© 2020 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more