TypeScript Conditional Types
Learn how to select types based on conditions using conditional type expressions, infer, distributive conditional types and never.
1. What are Conditional Types?
Conditional Types use a condition to choose between two possible types. They are similar to a ternary expression, but they operate on types rather than runtime values.
The condition checks whether one type extends another type. Depending on the result, TypeScript selects the appropriate type.
Basic Syntax
type Result<T> = T extends string ? "Yes" : "No";
type StringResult = Result<string>;
type NumberResult = Result<number>;
const result1: StringResult = "Yes";
const result2: NumberResult = "No";
console.log(result1);
console.log(result2);
Expected Output
Yes
No
StringResult becomes the type "Yes" because string extends string. NumberResult becomes the type "No" because number does not extend string.
2. Conditional Types Workflow Diagram
Follow this workflow to understand how TypeScript evaluates a type condition and selects the resulting type.
Define Condition
Specify a condition between types using extends.
Evaluate Type
TypeScript checks the relationship between the types.
Select Branch
Choose the true type or the false type.
Resulting Type
Use the selected type in other definitions.
3. Using extends in Conditional Types
The extends keyword checks whether a type is assignable
to another type. The conditional expression chooses one type when
the condition is satisfied and another when it is not.
Example
type IsNumber<T> = T extends number ? true : false;
type FirstResult = IsNumber<number>;
type SecondResult = IsNumber<string>;
const first: FirstResult = true;
const second: SecondResult = false;
console.log(first);
console.log(second);
Expected Output
true
false
How It Works
T = number
The condition is true, so the result type is true.
T = string
The condition is false, so the result type is false.
Type Result
The result is determined from T without runtime evaluation.
4. Conditional Types with Object Properties
Conditional Types can check whether a type contains a particular structure. This is useful for extracting a property's type only when the required property exists.
Example
type MessageOf<T> =
T extends { message: unknown } ? T["message"] : never;
type EmailMessage = MessageOf<{ message: string }>;
type CountMessage = MessageOf<{ message: number }>;
const emailMessage: EmailMessage = "Welcome";
const countMessage: CountMessage = 100;
console.log(emailMessage);
console.log(countMessage);
Expected Output
Welcome
100
When T contains a message property, MessageOf extracts its type. Here the property type is string for EmailMessage and number for CountMessage. If the required structure is absent, the resulting type is never.
5. Using infer in Conditional Types
The infer keyword allows TypeScript to infer a type
from a structure being checked by a conditional type.
It is useful when extracting a type from an array, function or other
generic structure.
Example: Extract Array Element Type
type ElementType<T> =
T extends readonly (infer Item)[] ? Item : T;
type NumberElement = ElementType<number[]>;
type StringElement = ElementType<string[]>;
type SingleValue = ElementType<boolean>;
const numberValue: NumberElement = 100;
const stringValue: StringElement = "TypeScript";
const booleanValue: SingleValue = true;
console.log(numberValue);
console.log(stringValue);
console.log(booleanValue);
Expected Output
100
TypeScript
true
If T is an array, Item is inferred as the array element type. If T is not an array, this conditional returns T unchanged.
infer Workflow Diagram
Input Type
Receive a type such as number[].
Check Array
Test whether T matches an array structure.
Infer Item
Capture the element type using infer Item.
Return Type
Produce the inferred element type.
6. Conditional Types with Function Types
Conditional Types can use infer to extract a function's return type. This illustrates the idea behind utility types such as ReturnType.
Example
type GetReturnType<T> =
T extends (...args: never[]) => infer Result ? Result : never;
type NumberFunction = () => number;
type StringFunction = () => string;
type NumberResult = GetReturnType<NumberFunction>;
type StringResult = GetReturnType<StringFunction>;
const numberResult: NumberResult = 500;
const stringResult: StringResult = "Success";
console.log(numberResult);
console.log(stringResult);
Expected Output
500
Success
The conditional type infers the return type and stores it in Result. A function returning number produces NumberResult as number, while a function returning string produces StringResult as string.
7. Distributive Conditional Types
A conditional type is distributive when the checked type is a naked type parameter. When a union is passed, TypeScript evaluates the conditional separately for each union member and combines the results.
Example
type ToArray<T> = T extends unknown ? T[] : never;
type StringOrNumberArray = ToArray<string | number>;
const names: StringOrNumberArray = ["Rahul", "Priya"];
const numbers: StringOrNumberArray = [10, 20, 30];
console.log(names);
console.log(numbers);
Expected Output
[ 'Rahul', 'Priya' ]
[ 10, 20, 30 ]
StringOrNumberArray becomes string[] | number[].
It permits an array of strings or an array of numbers.
Distribution Diagram
Union Input
string | number
Distribute
Evaluate the conditional for string and number separately.
Result
string[] | number[]
8. Preventing Distribution
Wrapping the checked type parameter in a tuple prevents a conditional type from distributing over a union. The entire union is evaluated as a single type.
Example
type OnlyStrings<T> =
T extends string ? T : never;
type OnlyStringsTogether<T> =
[T] extends [string] ? T : never;
type DistributedResult = OnlyStrings<string | number>;
type SingleCheckResult = OnlyStringsTogether<string | number>;
const validString: DistributedResult = "Hello";
console.log(validString);
// SingleCheckResult is never because the entire
// string | number union is not assignable to string.
Expected Output
Hello
DistributedResult becomes string because number is filtered out during distribution. SingleCheckResult becomes never because the entire union does not satisfy the string condition.
9. Understanding never in Conditional Types
The never type represents a type with no possible values.
Conditional Types often use it to exclude types that do not match
a specific requirement.
Example: Filtering a Union
type RemoveNumbers<T> =
T extends number ? never : T;
type RemainingTypes = RemoveNumbers<string | number | boolean>;
const textValue: RemainingTypes = "Hello";
const booleanValue: RemainingTypes = true;
console.log(textValue);
console.log(booleanValue);
Expected Output
Hello
true
The number member becomes never and is removed from the resulting union. RemainingTypes becomes string | boolean.
10. Practical Example: API Result Types
Conditional Types can select a type based on whether a response contains particular properties. This can help create reusable type transformations for different API response models.
Example
type ApiResult<T> =
T extends string
? { message: T }
: { data: T };
type MessageResult = ApiResult<string>;
type StudentResult = ApiResult<{ id: number; name: string }>;
const message: MessageResult = {
message: "Request completed"
};
const student: StudentResult = {
data: {
id: 101,
name: "Rahul"
}
};
console.log(message.message);
console.log(student.data.name);
Expected Output
Request completed
Rahul
Practical Workflow
Input Type
Supply either a string or a student object type.
Check Condition
Determine whether T extends string.
Select Structure
Produce either a message object or a data object.
11. Conditional Types Quick Reference
| Concept | Purpose | Example |
|---|---|---|
| Conditional Type | Selects a type based on a condition. | T extends U ? X : Y |
| extends | Checks type compatibility. | T extends string |
| infer | Infers a type from a matched structure. | infer Item |
| Distributive Conditional Type | Evaluates a naked type parameter union member by member. | T extends unknown ? T[] : never |
| Prevent Distribution | Checks the union as a whole. | [T] extends [U] |
| never | Represents no possible values and filters out union members. | T extends number ? never : T |
Summary
Conditional Types use T extends U ? X : Y to choose between
types. The infer keyword extracts a type from a matched structure.
Distributive conditional types process union members separately, while
tuple wrapping can prevent distribution. The never type is often used
to exclude types that do not meet a condition.
Next, learn Mapped Types and how to transform the properties of an existing type into a new type.