TypeScript escape hatches: unsafe operations
turning off type-checking partially or completely
For the following operations, we disable type-checking partially or entirely, either because we know something TypeScript doesn't know, or because we want to disable TypeScript temporarily
assert a value is non-nullish
We remove null and undefined from the value's type:
s // string | null | undefined
s! // string
assert a value conforms to a narrower type
We narrow down the type to a subset:
s // string | null | undefined
s as string // string
Note: in some scenarios, we type assert to a related type, not to a subset. The operation still requires the operation to be likely possible. If the operation is proven to be impossible because the types are incompatible, we must instead type assert to unknown first.
(do not use) assert a value conforms to an incompatible type
s // string | null | undefined
s as unknown as number // number
disable type-checking for a variable
let s: any
s = 3 // type-checker disabled
s = "foo" // type-checker disabled