Type guards thu hẹp type trong code branch.
Loại: 1) typeof, 2) instanceof, 3) in operator, 4) equality, 5) user-defined (function với return type is Type), 6) assertion functions.
typescript
function process(val: string | number | null) {
if (typeof val === 'string') return val.toUpperCase();
if (typeof val === 'number') return val.toFixed(2);
return 'null';
}
// User-defined guard (most powerful)
function isUser(obj: unknown): obj is { id: string; name: string } {
return typeof obj === 'object' && obj !== null && 'id' in obj;
}