capypad
0 day streak
typescript / beginner
Snippet

Type Assertions with 'as'

Type assertions are a way to tell the TypeScript compiler 'trust me, I know what I'm doing'. They treat an expression as a specific type without performing any special checking.

snippet.ts
typescript
1
2
let someValue: unknown = "Hello TypeScript";
let strLength: number = (someValue as string).length;
Breakdown
1
someValue as string
Tells TypeScript to treat 'someValue' as a string for this operation.
2
.length
Accesses the length property, which is valid because we asserted the value is a string.