BugCast
TS TypeScript

Type Narrowing & Type Guards

typeof, instanceof, discriminated unions — handle unknown types like a pro.

BugCast Admin··7 min read

Type Narrowing

TypeScript refines types within conditional blocks:

function print(value: string | number) {
  if (typeof value === "string") {
    console.log(value.toUpperCase()); // string
  } else {
    console.log(value.toFixed(2)); // number
  }
}

Discriminated Unions

type Result =
  | { status: "success"; data: User }
  | { status: "error"; message: string };

function handle(result: Result) {
  switch (result.status) {
    case "success":
      return result.data; // TypeScript knows shape
    case "error":
      return result.message;
  }
}

Custom Type Guards

function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    "name" in value
  );
}

Interview Questions

Q: unknown vs any?

unknown forces narrowing before use — type-safe. any bypasses all checks.

Q: What is exhaustive checking?

function assertNever(x: never): never {
  throw new Error("Unexpected: " + x);
}
// Use in default case to catch missing union members
#narrowing#type-guards#interview

Related posts