Concept Flow - Type assertions
Start with a value
Apply type assertion
Treat value as asserted type
Use value with new type
End
Type assertions tell TypeScript to treat a value as a specific type without changing the value.
let someValue: unknown = "hello"; let strLength: number = (someValue as string).length; console.log(strLength);
| Step | Action | Value | Type Before | Type After | Result |
|---|---|---|---|---|---|
| 1 | Declare someValue | "hello" | unknown | unknown | someValue holds "hello" |
| 2 | Assert someValue as string | "hello" | unknown | string | TypeScript treats someValue as string |
| 3 | Get length property | 5 | string | number | Length of string is 5 |
| 4 | Assign length to strLength | 5 | undefined | number | strLength is 5 |
| 5 | Console log strLength | 5 | number | number | Output: 5 |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| someValue | unknown ("hello") | unknown ("hello") | unknown ("hello") | unknown ("hello") |
| strLength | undefined | undefined | undefined | 5 |
Type assertions in TypeScript let you tell the compiler to treat a value as a specific type. Syntax: value as Type or <Type>value. They do not change the actual value at runtime. Use them when you know more about the type than TypeScript. Be careful to assert only compatible types to avoid runtime errors.