Type Assertions
A type assertion tells TypeScript you know more about a value than it can guess.
Use them sparingly.
They quiet the checker. They do not prove safety.
Narrowing is safer when you can do it.
as syntax
Write value as Type.
TypeScript allows assertions between related types.
Completely unrelated ones need a stop through unknown.
Unknown means we do not know the type yet.
Angle-bracket syntax
Older style uses angle brackets around the type.
Avoid it in .tsx files. It clashes with JSX.
JSX is the HTML like tags in React files.
Stick with as everywhere for consistency.
Non-null assertion
The postfix ! asserts a value is not null or undefined.
Only use it when you are sure.
A wrong ! can crash at runtime.
Runtime means while the program is running.
Const assertions
as const makes literals narrow.
Narrow means keep the exact word or number.
It also makes arrays or objects readonly.
Readonly means do not change them.
When assertions are ok
Assert when you have outside knowledge the compiler lacks.
Like a DOM element you just created yourself.
Do not hide a real type error behind as.
Assert when you have outside knowledge the compiler lacks. Do not hide a real type error.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.