TypeScriptUnions and narrowing
Type assertion (as)
Telling the compiler the type of a value when you know more than it does.
Example
#TypeScript
type Lesson = { title: string; minutes: number }
const raw = '{"title":"Grid","minutes":16}'
const lesson = JSON.parse(raw) as Lesson
console.log(lesson.title.toUpperCase(), lesson.minutes)Result
GRID 16
Definition and usage
#The assertion value as Type tells the compiler: “trust me, this is a Type”. It doesn’t change the value, and it checks nothing at runtime. It only affects the type at compile time.
Reasonable cases include a DOM element you know is a form field (as HTMLInputElement), or data that another layer of the application has already validated.
An overused assertion is a quiet back door for bugs. If the value actually has a different shape, the program only breaks at runtime. Wherever you can, use narrowing and type guards instead of as.
Syntax
#Syntax
const value = expression as TypeMore examples
#TypeScript
const broken = JSON.parse('{"name":"Grid"}') as Lesson
try {
console.log(broken.title.toUpperCase())
} catch (error) {
console.log('Runtime error, even though the compiler did not complain')
}Result
Runtime error, even though the compiler did not complain
Good practices
#- Treat
asas a last resort. For data from outside, it’s better to check its shape with a type guard. - A double assertion
as unknown as Talmost always means something is wrong with the types.
Related entries
#- as vs satisfiesas tells the compiler to trust your type and check nothing, while satisfies checks that the value matches the type and keeps the exact type inferred from the value.
- satisfiesChecks that a value matches a type without changing the inferred type.
- Type guards (value is T)Custom checking functions that narrow the type at the call site.
- Non-null assertion (!)An exclamation mark after an expression removes null and undefined from the type without checking.
- unknownThe safe counterpart to any: a value of an unknown type that you must check before use.
Spotted a mistake or missing an example? Write to us.