Learn TypeScript

Using type assertions

Using type assertions

In a TypeScript program, a variable can move from a less precise type to a more precise type. This process is called type narrowing, and we'll learn all about this in this module. We'll start in this lesson by learning how to use type assertions to narrow the type of a variable.

Understanding the need for type assertions

Type assertions are helpful when we know more about a variable value than TypeScript does. We are going to explore type assertions in the code editor below:

TypeScriptOpen exercise in CodeSandbox

The code contains a variable assignment from a DOM selector method.

🤔

What is the type of button?

  • Let's add code to disable the button:
if (button) {
button.disabled = true;
}
🤔

A type error occurs. Why is this so?

It would be nice to narrow the type of button to HTMLButtonElement so that TypeScript recognizes the disabled property. Type assertions allow us to do this.

Angle-bracket syntax

There are two types of syntax for a type assertion. The first is to define the type in angle-brackets just before the value or expression we are asserting:

<TypeName>expression;
  • Add the following type assertion to button on line 1:
const button = <HTMLButtonElement>document.querySelector(".go");
🤔

What is the type of button now?

Neat!

ESLint may warn about the use of the angle-bracket syntax because the "As" syntax is generally preferred. This is the case when using TypeScript in React apps because the React transpilation process may think the type assertion is a React component.

“As” syntax

The alternative and preferred syntax is to put the type after an as keyword after the expression:

expression as TypeName;
  • Update the code to use this syntax.

The inferred type of the button variable is still HTMLButtonElement.

Nice!

Summary

We can use type assertions in our code to tell the TypeScript what a type should be when it infers it incorrectly. We should prefer the as syntax when using a type assertion.

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