Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 96 ยท Basic Types

Type Assertions and the Non-Null Operator

Learn TypeScript type assertions - the as keyword, angle-bracket syntax, double assertions, the non-null ! operator, and how as differs from annotations and satisfies.

Sometimes you know more about a value than TypeScript does. A type assertion lets you tell the compiler, "trust me, this value has type T." You write it with the as keyword: value as T. The non-null assertion value! is a shortcut for one specific claim: "this is not null or undefined."

Assertions are useful, but they're also the easiest way to lie to the type checker. They change nothing at runtime: no conversion, no check, no error if you're wrong. This lesson shows when an assertion is the right tool, when it hides a bug, and which safer alternatives (annotations, narrowing and the satisfies operator) to reach for first.

The as keyword

The most common situation is a value whose type is too wide, such as the any that JSON.parse returns, or a union you've already checked in a way TypeScript can't follow:

TypeScript Asserting the type of parsed JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

After the assertion, config has the type Config, so autocompletion works and a typo like config.prot is an error. But read the assertion as a promise you make, not a check TypeScript performs. If the JSON had "port": "8080", the program would still compile, and config.port would quietly be a string at runtime. For data from outside your program, validate it instead; you'll learn how with type guards in this, Parameter Destructuring and Type Predicates and Typing APIs and JSON Data.

Assigning any to an annotated variable has the same effect: const config: Config = JSON.parse(text); compiles too, because any is assignable to everything. Both are unchecked. A safer habit is to treat parsed data as unknown and narrow it, as shown in any, unknown, never and void.

Angle-bracket syntax

There's an older, equivalent syntax that puts the type in angle brackets before the value:

TypeScript
const a = JSON.parse(text) as Config;   // modern
const b = <Config>JSON.parse(text);     // older, same meaning

Prefer as. The angle-bracket form is not allowed in .tsx files, because <Config> looks like a JSX element there. Since many projects mix .ts and .tsx, as works everywhere and is what you'll see in modern code. Linters such as typescript-eslint can enforce it.

Assertions must be plausible

TypeScript doesn't let you assert just anything. The source and target types must sufficiently overlap: one must be assignable to the other. Asserting from a wider type to a narrower one (unknown to string, Shape to Circle) is fine, and so is narrower to wider. Asserting between unrelated types is rejected. This example fails on purpose:

TypeScript An impossible assertion (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The compiler stops with:

TEXT
main.ts(2,16): error TS2352: Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

The message hints at an escape hatch: a double assertion through unknown (or any). Because everything is assignable to unknown and unknown can be asserted to anything, input as unknown as number compiles. Here's what that costs you. The example compiles and then crashes at runtime on purpose:

TypeScript A double assertion lies (crashes on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The first line prints string, because an assertion doesn't convert anything. Then length.toFixed(2) throws TypeError: length.toFixed is not a function. TypeScript was told length is a number, so it had no reason to warn you.

Treat as unknown as T as a red flag in code review. Legitimate uses exist (test doubles, low-level interop, working around a wrong library type), but each one deserves a comment explaining why. If you need a real conversion, convert: Number(input), String(n), parseInt(text, 10).

Asserting to a more specific type

Assertions also come up with unions, when you know which member you have but the code doesn't show it in a way TypeScript understands:

TypeScript Assertions versus narrowing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The wrong assertion prints wrong assertion: undefined, which is the worst kind of bug: no error, just a bad value flowing on. The area function shows the better pattern. Checking shape.kind narrows the union, and TypeScript proves the rest. You'll study this in Narrowing and Discriminated Unions. A good rule: if you can write a check, write the check; use an assertion only when the knowledge truly lives outside the code.

The non-null assertion operator (!)

Under strictNullChecks, many APIs return T | undefined or T | null: Map.get, Array.find, RegExp.exec, and DOM lookups like document.querySelector. If you're sure the value is there, a postfix ! removes null and undefined from the type.

First, the error you get without it. This example fails on purpose:

TypeScript Using a possibly undefined value (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The error is main.ts(7,13): error TS18048: 'apples' is possibly 'undefined'. TypeScript can't know which keys the map contains, so get returns number | undefined. Here are three ways to fix it, from the bluntest to the safest:

TypeScript Three ways to handle undefined

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The last line prints kiwis: undefined even though kiwis has the type number. Like as, the ! is erased when the code runs; it's purely an instruction to the type checker.

When is ! reasonable? When the "can't be missing" fact really is guaranteed by something TypeScript can't see: a key you just inserted, an element that's part of your own HTML template, a regular expression group that always matches. When the value could genuinely be missing, use ??, optional chaining ?., or an explicit check that throws a clear error.

The ! has a cousin on declarations: let id!: number; and class fields like name!: string; are definite assignment assertions. They tell TypeScript a variable will be assigned before use even though it can't prove it. You'll see them with strictPropertyInitialization in Classes.

Annotations, as and satisfies

TypeScript gives you three ways to connect a value with a type, and they behave differently:

  • Annotation (const x: T = value): the value is checked against T, and the variable gets type T. Extra details of the value are forgotten.
  • Assertion (const x = value as T): mostly unchecked (only the overlap rule applies), and the variable gets type T.
  • satisfies (const x = value satisfies T): the value is checked against T, but the variable keeps the value's own, more precise inferred type.

The difference is easiest to see side by side:

TypeScript Annotation, as and satisfies compared

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Why did the assertion accept an object without accent? An assertion only requires the types to overlap: Theme is assignable to { primary: 'red' }, so TypeScript allows the conversion in that direction. With an annotation or satisfies Theme, the missing property would be reported as an error. Assertions aren't completely blind, though: asserting { primary: 'red', accent: 'gren' } as Theme is rejected with TS2352, because the string 'gren' can't overlap with any allowed accent value.

As a rule of thumb, prefer them in this order:

  1. Let inference work, or narrow with checks.
  2. Use an annotation when you want a variable to have exactly a declared type, such as a function's parameters and return values.
  3. Use satisfies when you want validation without losing detail, typical for configuration objects and lookup tables. The satisfies Operator goes deeper.
  4. Use as only for knowledge the compiler can't have, and keep it as narrow as possible.

as const is not a type assertion

as const looks like an assertion but does something different: it asks TypeScript to infer the narrowest type for a literal, with readonly properties and literal types instead of string or number. It's always safe, because it doesn't claim anything that isn't true:

TypeScript
const sizes = ['s', 'm', 'l'] as const; // readonly ['s', 'm', 'l']

It's covered in Literal Types and as const. You can even combine it with satisfies: { ... } as const satisfies Config keeps literal types and validates the shape.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does console.log(typeof ("42" as unknown as number)) print at runtime?

    Assertions are erased and never convert values. The value is still the string '42', so typeof gives 'string'.
  2. 2. Does const n = true as string; compile?

    An assertion is only allowed when one type is assignable to the other. For unrelated types you would need a double assertion through unknown, which is a red flag.
  3. 3. Why is <User>data not allowed in a .tsx file?

    In TSX, <User> looks like a JSX tag. The as syntax works in every file type, which is why it is the standard.
  4. 4. const m = new Map<string, number>(); const v = m.get('x')!; What is the runtime value of v?

    The non-null assertion is erased. The map has no 'x' key, so v is undefined at runtime even though its type is number.
  5. 5. Which option checks a value against a type but keeps the more precise inferred type of the value?

    satisfies validates the value against T without changing the variable's type to T, so literal types, tuples and specific property types are preserved.

Summary

  • value as T tells TypeScript to treat a value as type T. It is not checked beyond a basic overlap rule, and it does nothing at runtime.
  • The angle-bracket form <T>value means the same but doesn't work in .tsx; prefer as.
  • Unrelated types are rejected with error TS2352. as unknown as T bypasses that and should be rare and commented.
  • Prefer narrowing (checks on kind, typeof, in) over asserting union members.
  • The postfix ! removes null and undefined from a type. It's erased, so a wrong ! still produces undefined later; prefer ??, ?. or an explicit check when the value can be missing.
  • Annotations check and widen, as asserts without checking, satisfies checks and keeps the inferred type. as const asks for the narrowest literal type and is always safe.

Next: Typing Functions