QA
Intermediate LevelJavaScript & TypeScript

What are TypeScript Union and Intersection types and how do type guards work?

❓ Interview Prompt: Compare Union types (|) vs Intersection types (&) and explain type narrowing with typeof, instanceof, and in operators.

Union Types (A | B):

A value that can be either type A OR type B. TypeScript only allows accessing properties shared by ALL members of the union until narrowed.

Intersection Types (A & B):

Combines multiple types into one, requiring the value to satisfy ALL features of type A AND type B simultaneously.

Type Narrowing (Type Guards):

Techniques to narrow down a broad union to a specific concrete type inside a conditional block:

1
typeof val === 'string'
2
val instanceof Date
3
'key' in obj

Code Implementation Example

typescript
type User = { name: string };
type Admin = { permissions: string[] };

// Intersection: must have both name AND permissions
type AdminUser = User & Admin;
const superUser: AdminUser = { name: 'Alice', permissions: ['read', 'write'] };

// Union with type narrowing guard
function processInput(input: string | number | Date) {
  if (typeof input === 'string') {
    return input.toUpperCase(); // TS narrowed to string
  } else if (input instanceof Date) {
    return input.toISOString(); // TS narrowed to Date
  } else {
    return input.toFixed(2);    // TS narrowed to number
  }
}
💡Intersection type creation and union type narrowing with typeof and instanceof.
🎯 Interview Key Takeaway

Unions represent OR types requiring narrowing; intersections represent AND types combining multiple interface contracts.

#TypeScript#Unions#Intersections#Type Guards#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)?