0Pricing
TypeScript Academy · Lesson

Double Assertions and Their Risks

When as unknown as T is needed and why it is dangerous.

What Is a Double Assertion?

A double assertion chains two as casts, usually through unknown: value as unknown as T. It forces a conversion the compiler would otherwise reject.

const s = 'hello';
const n = s as unknown as number; // forced
console.log(typeof n); // still 'string' at runtime!

Why TS Blocks Direct Casts

TypeScript blocks s as number when string and number don't overlap, because it's almost certainly a mistake. The error protects you from nonsensical assertions.

const s = 'text';
// const n = s as number; // Error: types do not sufficiently overlap
console.log('Direct unrelated assertion is rejected');

All lessons in this course

  1. The as Keyword for Type Assertions
  2. Non-null Assertion Operator
  3. Double Assertions and Their Risks
  4. Assertions vs Type Guards
← Back to TypeScript Academy