What Are Conditional Types in TypeScript?

Understanding Conditional Types in TypeScript with Real Examples

Conditional types in TypeScript let you create a type that depends on another type.
Think of them like if/else for types. They’re super useful when you want
to return different types depending on what input type you get.

The Syntax

The basic syntax looks like this:

T extends U ? X : Y
//Reads as: If type T can be represented as U, then we use type X, otherwise — Y.

A Simple Example

type IsString<T> = T extends string ? "yes" : "no";

type A = IsString<"hello">;  // "yes"
type B = IsString<42>;       // "no"

Real-Life Example: API Response

Let’s say you have an API that returns different responses depending on the request.
You can define a conditional type to match each case:

type ApiResponse<T> = 
  T extends "user" ? { id: number; name: string } :
  T extends "product" ? { id: number; price: number } :
  never;
  
//Now you can create a function that returns the correct type based on the input.
function getData<T extends "user" | "product">(type: T): ApiResponse<T> {
  if (type === "user") {
    return { id: 1, name: "Alice" } as ApiResponse<T>;
  } else {
    return { id: 2, price: 99.99 } as ApiResponse<T>;
  }
}

const user = getData("user");     // { id, name }
const product = getData("product"); // { id, price }

Another Use Case: Forms

If you are making a UI where form fields depend on the selected type, you can do it like this:

type FormFields<T> = 
  T extends "login" ? { username: string; password: string } :
  T extends "register" ? { username: string; password: string; email: string } :
  never;
function renderForm<T extends "login" | "register">(type: T, data: FormFields<T>) {
  // data will be strongly typed based on the form type
}

renderForm("login", { username: "me", password: "1234" }); // OK
renderForm("register", { username: "me", password: "1234", email: "me@site.com" }); // OK
renderForm("login", { username: "me", password: "1234", email: "extra" }); // ❌ Error!

Nested Conditions

type TypeCheck<T> = 
  T extends string ? "string" :
  T extends number ? "number" :
  "something else";

When Should You Use Conditional Types?

  • In reusable libraries (React, Vue components)
  • When handling API types
  • To make smart form logic
  • When building helpers like Exclude or ReturnType

Conditional types help you write smarter and safer TypeScript code.
They keep your code flexible while avoiding runtime bugs —
and once you get the hang of them, you’ll want to use them all the time!

Leave a Reply

Your email address will not be published. Required fields are marked *