Type Assertions with as

What is a Type Assertion?

A type assertion (value as Type) tells TypeScript "trust me, I know the type better than you". It does not convert or check anything at runtime; it only changes what the compiler believes.

Example

A classic browser example is document.getElementById("email") as HTMLInputElement. Here we assert the type of parsed JSON we trust.

type Config = { appName: string; maxCartItems: number };

const raw = '{"appName": "ShopEase", "maxCartItems": 20}';
const config = JSON.parse(raw) as Config;

console.log(config.appName, config.maxCartItems);

Output

ShopEase 20

Impossible Assertions Are Rejected

Example

TypeScript only allows an assertion when the types overlap. string as number is error TS2352.

const price = "499";
const n = price as number;

Compiler output (tsc)

Line 2: 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.

Note: You may see value as unknown as T (double assertion) to force anything. It is almost always a code smell.

Angle-bracket Syntax

<Config>value is the older form of value as Config. It does not work in .tsx files (it looks like JSX), so always use as.