TypeScript Assertion Patterns
Learn when and how to use type assertions carefully without breaking type safety.
David Miller
December 1, 2025
3.2k121
Type assertions tell TS: trust me, I know the type.
## Basic assertion
```ts
const el = document.getElementById("app") as HTMLDivElement;
el.innerHTML = "Hello";
```
## Angle bracket (not in JSX)
```ts
const val = <string>someValue;
```
## Dangerous example
```ts
const n = "hello" as unknown as number;
```
This can break logic.
## Safer pattern: runtime check
```ts
const el = document.getElementById("app");
if (el instanceof HTMLDivElement) {
el.innerHTML = "Safe";
}
```
## Graph
```mermaid
flowchart TD
A[Unknown Value] --> B[Assertion]
B --> C[Trusted Type]
```
## Remember
- Assertions bypass checks
- Prefer type guards first
- Use only when you are sure
#TypeScript#Advanced#Assertions