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
- The as Keyword for Type Assertions
- Non-null Assertion Operator
- Double Assertions and Their Risks
- Assertions vs Type Guards