ProgramGuru

Type Assertions

Learn Type Assertions

A type assertion uses as to tell TypeScript how to interpret a value statically, without converting or validating it at runtime.

In this lesson, you will study the rule, run a complete TypeScript example, explain its output, and test a small change.

What you’ll learn

  • Explain the main rule behind type assertions.
  • Predict the result of the complete runnable TypeScript example.
  • Recognize one common mistake and correct it.

Understand the concept

Assertions are sometimes needed when you know more than the checker can infer. For external data, always verify the claim with runtime conditions or schema validation first. An assertion is removed during emission and cannot make an incorrect value safe.

Run a complete TypeScript example

Save this code as main.ts or paste it into the TypeScript Playground. The example uses fixed values so it runs without prompting for input.

TypeScript code

const input: unknown = "42";
 if (typeof input === "string") {
   const text = input as string;
   console.log(text.length);
 }

Verified output

2

How to run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. When using a project configuration, run the matching project build instead.

Trace the execution

The typeof guard makes the string assertion redundant in this example, deliberately showing that as string changes neither the value nor its length. The program prints 2.

Predict the output before you run the sample. Compare each line with the source expression that produced it, and distinguish the type checker’s work from what happens in JavaScript at runtime.

Common mistakes and how to avoid them

Writing "42" as number is not parsing. Number("42") performs a conversion; as number does not.

Debugging habit: when a change is rejected, read the exact compiler diagnostic and inspect the operand types. When it compiles but behaves unexpectedly, follow the values through the JavaScript expressions.

Practice it yourself

Remove the redundant as string and verify the same output. Compare Number("42") with a type assertion in the editor.

Challenge: write down your prediction first, run the changed source, and explain any difference. Return to the verified version before continuing.

Check your understanding

Which expression converts the string "42" to a number at runtime?
Choose one answer. You can try again.

Answer and explanation

Number("42")

Number is a real JavaScript conversion function; assertions are erased.

Review the key idea

Type Assertions: Assertions are sometimes needed when you know more than the checker can infer.

Number is a real JavaScript conversion function; assertions are erased.

Before continuing, be able to explain what is checked before execution and what actually changes at runtime in the example above.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Non-Null Assertions →