Course contentsShow
← TypeScript
Lesson 811 of 1,79618. Conditional TypesFree lesson

Creating Type Guards as Types

Build conditional types that narrow unions based on property presence, mimicking runtime type guard logic.

Creating Type Guards as Types

You'll learn: How to build conditional types that mimic type guard logic, narrowing unions based on whether a property exists — all at the type level.


The Core Idea

You already know type guards as runtime functions that narrow types:

function isUser(x: unknown): x is User {
  return typeof x === 'object' && x !== null && 'username' in x;
}

But what if you want that same narrowing logic at the type level? Conditional types let you filter union members based on whether they have a specific property, effectively creating "type guards as types."


Building a Type-Level Type Guard

Use a conditional type with extends and property checking:

type HasStatus<T> = T extends { status: unknown } ? T : never;

type A = { status: number; id: string };
type B = { id: string };
type C = { status: string; name: string };

type Result = HasStatus<A | B | C>;
// Result is A | C — B is filtered out because it lacks 'status'

How it works:

  • The conditional distributes over the union A | B | C
  • For each member, it checks: does this type extend { status: unknown }?
  • If yes, keep it (T); if no, discard it (never)
  • never members vanish from the union

Analogy: A Bouncer at the Door

Imagine a union is a line of people trying to enter a club. Your type guard is the bouncer checking for a "status badge." Those with the badge ({ status: ... }) get in; those without are turned away (never).


Practical Example

type WithTimestamp<T> = T extends { timestamp: unknown } ? T : never;

type Action = 
  | { type: 'LOGIN'; user: string }
  | { type: 'LOGOUT'; timestamp: number }
  | { type: 'REFRESH'; timestamp: number; token: string };

type TimestampedActions = WithTimestamp<Action>;
// Only the LOGOUT and REFRESH actions remain

You've created a type that filters union members by property presence, just like a runtime type guard — but at compile time.


Key Takeaway: Conditional types with extends { property: unknown } let you build type-level guards that narrow unions based on shape, filtering members without writing runtime code.