Skip to content
jshacks.dev
TypeScript

Type Annotations vs Type Assertions

A type annotation asks the compiler to check a value, while an assertion tells it to trust you. Learn the difference, the errors and safer alternatives.

6 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the TypeScript, Node.js, npm and JavaScript logos.

Two pieces of TypeScript syntax look alike and do opposite jobs. Writing const n: number = value asks the compiler to verify that value is a number. Writing const n = value as number tells the compiler to treat value as a number whether or not it can prove it. The first is a check, and the second is a promise from you that the compiler cannot verify. Mixing them up is one of the most common sources of bugs that TypeScript was supposed to prevent. This post explains each, shows the exact compiler messages, covers the assertion forms including the non-null operator and as const, and offers safer alternatives. It uses TypeScript 6.x, and the rules are in the everyday types page of the handbook.

What an annotation does

A type annotation declares the type a variable, parameter or return value is meant to have. The compiler then checks every value assigned to it, and reports an error when one does not fit.

annotate.tsTypeScript
const total: number = "5";
const label: string = String(5);
Text
annotate.ts(1,7): error TS2322: Type 'string' is not assignable to type 'number'.

The first line fails because "5" is a string. The second passes, because String(5) returns a string. The compiler does the work here: it compares the type of the value with the declared type, and it refuses to continue when they disagree. An annotation is a contract that the compiler enforces on your behalf, and the contract is only as good as the check.

The same applies to parameters and returns. A function declared as function parse(text: string): number is checked in two directions. Callers must pass a string, and the body must return a number. If someone later changes the body so that one path returns undefined, the compiler reports it.

What an assertion does

A type assertion changes the type the compiler believes a value has, without any runtime check. The syntax is value as Type. It exists for cases where you know something the compiler cannot, for example after reading an element from the DOM.

assert.tsTypeScript
const input = document.getElementById("email") as HTMLInputElement;
console.log(input.value);

getElementById returns HTMLElement | null, because the compiler cannot know which element has that id or whether it exists. The assertion says: this one is an input. After it, input.value is allowed, because HTMLInputElement has a value property. If the element is actually a div, or missing, the program fails at runtime with TypeError: Cannot read properties of null (reading 'value'). The compiler accepted your claim and the runtime did not.

This is the central difference. An annotation moves responsibility to the compiler. An assertion keeps responsibility with you. Both erase to nothing in the emitted JavaScript, so neither adds a runtime check, but only the annotation gets a compile-time one.

What the compiler does refuse

Assertions are not unlimited. The compiler allows an assertion only when the two types overlap enough that one could plausibly be the other. If they are unrelated, it reports an error.

bad-assert.tsTypeScript
const raw = "42";
const n = raw as number;
Text
bad-assert.ts(2,11): 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.

That message is also a hint at how people defeat the check: write raw as unknown as number. Passing through unknown removes the overlap test, and the compiler accepts it. Doing so should feel uncomfortable. You are telling the compiler to believe something it just told you is probably wrong, and the number you use later will still be the string "42" at runtime. If you need a number, convert it with Number(raw), and let the type follow from the conversion.

Assertions are fine for narrowing to a more specific type that you have good reason to trust, such as from HTMLElement to HTMLInputElement. They are a poor tool for turning one unrelated type into another.

The non-null assertion

A close relative is the postfix ! operator, which asserts that a value is not null or undefined.

nonnull.tsTypeScript
const el = document.getElementById("email");
console.log(el.textContent);
console.log(el!.textContent);
Text
nonnull.ts(2,13): error TS18047: 'el' is possibly 'null'.

With strict enabled, the first access is reported because getElementById may return null. The ! on line 3 removes the error, which shows what the operator does: it strips null and undefined from the type, and nothing else. It does not make el an input. Like as, the ! is a claim with no runtime check, and if the element is missing, the code throws a TypeError when it reads the property.

Prefer a real check. An if (el === null) throw new Error("#email not found") costs one line, narrows the type for the rest of the function and fails with a message that tells you what went wrong, where the assertion fails with a generic TypeError later.

Const assertions

There is one assertion that is not a risky claim at all: as const. It tells the compiler to infer the narrowest possible type for a literal, making object properties read-only and arrays into tuples.

constant.tsTypeScript
const config = { mode: "dark", retries: 3 } as const;

config.mode = "light";
Text
constant.ts(3,8): error TS2540: Cannot assign to 'mode' because it is a read-only property.

Here the assertion adds information in the safe direction. It narrows the type from { mode: string; retries: number } to { readonly mode: "dark"; readonly retries: 3 }, and every property is known exactly. Nothing is being overridden, because the compiler can see the literal. This is the kind of assertion to use freely.

Annotation, assertion or satisfies

The satisfies operator sits between the two, and it fixes a common problem. If you annotate a variable, the annotation replaces the inferred type, so you lose precise information. If you assert, you lose the check. With satisfies, the compiler verifies that the value fits a type and keeps the more specific inferred type.

satisfy.tsTypeScript
type Theme = { mode: "light" | "dark"; accent: string };

const theme = { mode: "dark", accent: "#336" } satisfies Theme;
const bad = { mode: "dim", accent: "#336" } satisfies Theme;
Text
satisfy.ts(4,15): error TS2322: Type '"dim"' is not assignable to type '"light" | "dark"'.

The first declaration passes, and theme.mode keeps the literal type "dark", not the wider union. The second is rejected because "dim" is not one of the allowed modes, and the error points at the property. You get validation without giving up inference, which makes satisfies the right choice for configuration objects and lookup tables.

How to choose

Use an annotation when you want the compiler to enforce a type at a boundary: function parameters, return types, exported constants, empty collections. Use satisfies when you want a check but also want the precise inferred type to stay. Use as const to freeze a literal's type. Use as for a narrowing you can justify in a comment, and for the DOM and similar cases where the compiler lacks information that you have. Avoid as unknown as T and the non-null ! unless you can name why the value cannot be wrong.

Data from outside the program is the area where assertions do the most damage. JSON.parse(text) as User compiles and tells the rest of the program that the data has a shape that nothing verified. A server returning a different shape produces failures far from the cause. Validate the data with a schema or a hand-written guard function, which returns a type predicate such as value is User, and let the narrowed type come from the check.

A review habit

When you read code, treat each as as a place where the compiler stopped helping, and ask whether a check, a guard or satisfies could replace it. A codebase with a few well-explained assertions around the DOM and integrations is healthy. One with assertions scattered through business logic is a sign that the types were fitted to the code by force, which defeats the reason for using TypeScript.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.