TypeScript's powerful type inference engine relies on Type Narrowing—the process of refining a broad type into a more specific type within a conditional code block.
1. Type Guards: typeof, instanceof, and in
function formatInput(val: string | number | Date) {
if (typeof val === "string") {
return val.toUpperCase(); // Narrowed to string
}
if (val instanceof Date) {
return val.toISOString(); // Narrowed to Date
}
return val.toFixed(2); // Narrowed to number
}2. Custom Type Guard Functions (is Keyword)
interface User { id: string; name: string; }function isAdmin(user: User): user is Admin { return "permissions" in user && Array.isArray((user as Admin).permissions); } ```
3. Discriminated Unions & Exhaustiveness Checking
A Discriminated Union is a union type where every member shares a common literal property (the discriminant).
type NetworkState =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: string[] }function renderUI(state: NetworkState): string {
switch (state.status) {
case "idle": return "Ready";
case "loading": return "Loading...";
case "success": return Loaded ${state.data.length} items;
case "error": return Error: ${state.error.message};
default: {
const _exhaustiveCheck: never = state;
return _exhaustiveCheck;
}
}
}
```
---
Practice TypeScript Interviews Live Evaluate candidate TypeScript type safety live in a collaborative editor. [Create a Free Pairlet Room](https://www.pairlet.dev/interview/new).
Conduct Live Coding Interviews with Zero Friction
No candidate sign-up required. Create an instant room, share the link, and code together in real time with shared code execution.