liveBook · Manning

Type assertion

As explained in Essential TypeScript 5, Third Edition

A type assertion is a TypeScript construct that tells the compiler to treat an expression as a specified type without performing a runtime type conversion.

A type assertion tells TypeScript to check an expression as a specified type. Write the expression followed by `as` and the type. This is useful when you know something about a value that the compiler cannot establish, but it does not convert or validate the value at runtime. section 7.4 section 2.4.3

Select a type from a union

In `src/index.ts`, `calculateTax(100, false)` returns a number, while `calculateTax(100, true)` returns a formatted string. The declared return type is `string | number`, so assertions permit operations specific to each result: `let taxNumber = calculateTax(100, false) as number;` and `let taxString = calculateTax(100, true) as string;`. The first can use `toFixed(2)`; the second can use `charAt(0)`. These assertions depend on the calls behaving as expected. section 7.4

Listing 7.23 Using type assertions in the index.ts file in the src folder
function calculateTax(amount: number, format: boolean): string | number {
    const calcAmount = amount * 1.2;
    return format ? `$${calcAmount.toFixed(2)}` : calcAmount;
}

let taxNumber = calculateTax(100, false) as number;
let taxString = calculateTax(100, true) as string;
 
console.log(`Number Value: ${taxNumber.toFixed(2)}`);
console.log(`String Value: ${taxString.charAt(0)}`);

The complete `src/index.ts` listing shows the union return type, both assertions, and the type-specific method calls together. section 7.4

Keep the compiler's warning and the runtime value separate:

  • An assertion from `string | number` directly to `boolean` produces an error because `boolean` is not an expected type. Usually, correct the union or the assertion instead. section 7.4.1
  • A double assertion through `any` can suppress that warning, but it cannot turn a number into a boolean: the example still prints `120`. Use this escape hatch only when you can take responsibility for the actual value. section 7.4.1

Read a DOM event target

In `src/productItem.tsx`, a quantity-change handler reads `Number((ev.target as HTMLSelectElement).value)`. The assertion lets the handler access the select element's `value`; `Number(...)`, not the assertion, performs the conversion used for the quantity. section 16.8.1

Assertions also appear where inference is too restrictive: an empty array may be inferred as `never` under the shown `strictNullChecks` configuration, and a conditional return type may require an `as any` assertion when the compiler cannot correlate its branches. Consider whether a better initialization or type description can avoid overriding the checker. section 9.2.3 section 13.6.2

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Explains `as` syntax, union narrowing, rejected assertions, double assertions, and unchanged runtime values; does not present assertions as validation.
Examples
Uses a tax function returning strings or numbers, a task-selection answer, and a select-element quantity handler.
What it assumes
Builds on JavaScript values and TypeScript union types while introducing the assertion syntax directly.
What you can do after
Apply it via TypeScript's `as` syntax to access an expected type's members while checking that the runtime value matches.
How it connects
Connects type assertions to type unions, type guards, `any`, conditional types, and DOM event handling.

Also explained in

Compare how 5 books explain type assertion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.