

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Narrowing Types
incomplete
2: Unknown Type
incomplete
3: Type Hierarchy
incomplete
4: Narrowing Using In
incomplete
5: Type Predicates
incomplete
6: Exhaustive Checks
incomplete
7: Guard Clauses
incomplete
8: Type Assertion
incomplete
9: Double Assertion
incomplete
10: Non-Null Assertion
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
TypeScript won't allow you to assert absolute nonsense:
const num = 42;
// Error: Conversion of type 'number' to type
// 'string' may be a mistake because neither
// type sufficiently overlaps with the other.
const str = num as string;
The number and string types have no overlap, making this assertion likely to be a mistake, so TypeScript complains. We can get around this with a double assertion:
const id = 42;
// This works - but is very unsafe!
const userId = id as unknown as string;
// Now TypeScript treats this as a string
console.log(userId.toUpperCase());
// Compiles, but still CRASHES at runtime!
I've never used this in production code. If you see this in the wild, pray that the author was a 100x engineer that knew what they were doing.