QA
Intermediate LevelJavaScript & TypeScript

What are Type Narrowing strategies in TypeScript (in, instanceof, typeof, equality, discriminated unions)?

❓ Interview Prompt: Summarize all native control flow type narrowing mechanisms available in TypeScript.

Type Narrowing is the process where TypeScript refines a broad type into a narrower, more specific type based on conditional logic checks in code.

Exhaustive List of Narrowing Strategies:

1
`typeof` Guard: For primitive types (typeof x === 'string').
2
`instanceof` Guard: For class instances (x instanceof Date).
3
`in` Operator Guard: Checks for property existence ('error' in response).
4
Equality Guard: Strict equality checks (x === 'admin').
5
Discriminated Union: Shared literal property tag check.
6
Truthiness Check: Null/undefined filtering (if (x) { ... }).

Code Implementation Example

typescript
type NetworkState =
  | { status: 'loading' }
  | { status: 'success'; data: string }
  | { status: 'error'; error: Error };

function handleState(state: NetworkState) {
  // Discriminated union narrowing on 'status' property
  switch (state.status) {
    case 'loading':
      return 'Loading...';
    case 'success':
      return state.data.toUpperCase(); // TS narrows to success state!
    case 'error':
      return state.error.message;     // TS narrows to error state!
  }
}
💡Discriminated union type narrowing inside switch statement.
🎯 Interview Key Takeaway

TypeScript relies on control flow analysis to narrow types within conditional checks like typeof, instanceof, and in operators.

#TypeScript#Type Narrowing#Discriminated Unions#Intermediate
Back to all JavaScript & TypeScript Questions→

More JavaScript & TypeScript Interview Questions

Beginner LevelJavaScript & TypeScript

What are the differences between var, let, and const in JavaScript?

Beginner LevelJavaScript & TypeScript

What are the JavaScript data types and the difference between primitives and objects?

Beginner LevelJavaScript & TypeScript

What is the difference between == (loose equality) and === (strict equality)?