Conditional Types with Primitives
What you'll learn: How to create conditional types that branch based on whether a type is string, number, boolean, or other primitive types.
The Core Idea
Conditional types let you ask TypeScript "is this type X?" and then give different type answers based on the result. With primitives, you're checking if a type extends a specific primitive like string or number, then returning one type if true and another if false.
Think of it like a type-level if/else statement that works with the basic building blocks of JavaScript.
Basic Primitive Branching
The simplest pattern checks a single primitive:
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<number>; // false
type C = IsString<boolean>; // false
Multiple Primitive Checks
You can create conditional types that distinguish between different primitives:
type TypeName<T> =
T extends string ? "string" :
T extends number ? "number" :
T extends boolean ? "boolean" :
"other";
type D = TypeName<"text">; // "string"
type E = TypeName<42>; // "number"
type F = TypeName<true>; // "boolean"
type G = TypeName<symbol>; // "other"
Practical Use: Format Values by Type
type Format<T> = T extends number ? `${T}px` : T extends boolean ? "yes" | "no" : T;
type Width = Format<16>; // "16px"
type Flag = Format<true>; // "yes" | "no"
type Name = Format<"John">; // "John"
Key Takeaway: Conditional types with primitives let you create type-level logic that branches on whether a type is string, number, boolean, or other basic types, enabling type transformations based on the fundamental nature of your data.