TExcelTAD
Home › TypeScript › TS Casting

TypeScript Casting

Sometimes you know more about a value than the compiler does. Maybe you just parsed some JSON and you know its shape, or a library returns a general type and you know the specific one. Type assertions (often called casting) let you tell the compiler "trust me, treat this value as type X".

There is one crucial difference from casting in languages like Java or C#: a TypeScript assertion does nothing at runtime. It does not convert, check or change the value. It only changes what the type checker believes.

The as keyword

ts · try it yourself
const raw: unknown = "typescript";

// console.log(raw.length);           // error: 'raw' is of type 'unknown'
console.log((raw as string).length);
console.log((raw as string).toUpperCase());
10
TYPESCRIPT

unknown blocks every operation until you narrow it or assert it. The assertion raw as string lets us call string methods.

Assertions don't convert values

Because assertions are erased, asserting the wrong type produces wrong behaviour instead of an error:

ts · try it yourself
const input: unknown = 42;
const text = input as string;

console.log(typeof text);
console.log(text + 1);
number
43

The compiler thinks text is a string, so it expects text + 1 to be "421". At runtime it is still the number 42. To actually convert, use JavaScript functions:

You want Use
number → string String(n), n.toString(), `${n}`
string → number Number(s), parseInt(s, 10), parseFloat(s)
anything → boolean Boolean(x) or !!x

Impossible assertions are rejected

TypeScript does protect you from assertions that make no sense. You may assert to a type that is more specific or more general, but not to an unrelated one:

ts · try it yourself
const count = 5;
const label = count as string;
main.ts(2,15): error TS2352: Conversion of type 'number' to type 'string' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

The message suggests the escape hatch: count as unknown as string. That "double assertion" compiles, but it is almost always a sign you should convert the value instead.

Asserting object shapes

A common use is giving a type to data whose shape you trust, such as parsed JSON:

ts · try it yourself
interface User {
  id: number;
  email: string;
}

const json = '{"id": 7, "email": "mai@example.com"}';
const user = JSON.parse(json) as User;

console.log(user.id, user.email.split("@")[1]);
7 example.com

JSON.parse returns any, so the assertion mostly documents intent and gives you autocompletion. If the data could be malformed, validate it with real runtime checks instead (see the Narrowing lesson).

Angle-bracket syntax

An older syntax writes the type in angle brackets before the value: <string>raw. It means the same as raw as string, but it cannot be used in .tsx files because it clashes with JSX tags, so modern code uses as everywhere.

Non-null assertion !

A postfix ! removes null and undefined from a type: value! says "this is definitely not null".

ts · try it yourself
const prices = new Map<string, number>([["tea", 3], ["coffee", 4]]);

const tea = prices.get("tea")!;      // number, not number | undefined
console.log(tea * 2);
6

Warning: Every assertion is a promise the compiler cannot check. Prefer narrowing (if, typeof, in) when you can; reserve as and ! for cases where you genuinely know better.

as const

as const is a special assertion that makes a value as narrow and read-only as possible — literals stay literals and arrays become read-only tuples. It is covered in the Literal Types lesson.

Test yourself

What does value as string do at runtime?

  1. Converts the value with String()
  2. Throws if the value isn't a string
  3. Nothing — it only affects type checking
  4. Calls toString() on the value

Why is 5 as string a compile error?

  1. Numbers can't be asserted
  2. The types don't sufficiently overlap
  3. as only works on objects
  4. You must use <string> syntax

What does the postfix ! in map.get(key)! do?

  1. Negates the value
  2. Removes null and undefined from the type
  3. Throws if the key is missing
  4. Makes the value read-only