Conditional types introduce highly dynamic logic directly into the type system itself.
They allow a type to change depending on the conditions of another generic input.
The syntax looks exactly like a standard JavaScript ternary operator (condition ? true : false).
This capability enables developers to write incredibly flexible and reusable libraries.
A conditional type takes the form T extends U ? X : Y.
If the generic type T is assignable to U, the resulting type resolves to X.
If it does not match, it falls back and resolves to the alternate type Y.
This allows your APIs to respond intelligently based on the data provided to them.
// If T is a string, resolve to true, else resolve to false type IsString<T> = T extends string ? true : false;type A = IsString<"Hello">; // Resolves to literal 'true' type B = IsString<100>; // Resolves to literal 'false'
Conditional types become extremely powerful when paired with the infer keyword.
The infer keyword allows you to extract and assign a nested type into a new variable.
This is widely used to unwrap Promise types or figure out the return type of a function.
It is the secret mechanism behind many complex built-in utility types.
// Extract the return type from any given function type GetReturnType<T> = T extends (...args: any[]) => infer R ? R : never;function generateId() { return "ID-12345"; }
// ExtractedType becomes strictly a 'string' type ExtractedType = GetReturnType<typeof generateId>;
By utilizing conditional types, you keep your source code highly modular and drastically smaller.
Smaller codebases parse and build significantly faster in continuous integration environments.
Fast, reliable builds lead to rapid deployment of crucial SEO content updates.
They prevent you from having to write and maintain dozens of repetitive interface overloads.
type MessageResponse<T> = T extends "error"
? { errorCode: number }
: { successData: string };
let res: MessageResponse<"error"> = { errorCode: 404 };
Which keyword is used within a conditional type to dynamically extract a sub-type?
Conditional types are a strictly advanced topic primarily used by library maintainers.
They provide an unparalleled level of generic flexibility in the TypeScript ecosystem.
Next, we will learn how to iterate over objects using Mapped Types!