capypad
0 day streak
typescript / beginner
Snippet

Type Guards with typeof

Type guards use runtime checks to narrow down a union type to a specific type within a block of code.

snippet.ts
typescript
1
2
3
4
5
6
function format(value: string | number) {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}
Breakdown
1
if (typeof value === "string")
A runtime check that tells TypeScript the value is definitely a string inside this block.
2
value.toUpperCase();
Safe to call because TypeScript knows 'value' is a string here.