Sub topic 6
Quick Refresher: Conditional Types and `infer`
This chapter assumes you know basic TypeScript types, type aliases, string literal unions, generics, and mapped types. You should also be comfortable reading a type such as T extends string.
Conditional types and infer are the tools that let a type ask questions about another type. Template literal types later use the same tools to match and extract parts of strings.
Conditional types choose between two types
A conditional type has this shape:
type Result<T> = T extends SomeType ? TypeIfTrue : TypeIfFalse;Read T extends SomeType as “does T fit SomeType?” If the answer is yes, TypeScript chooses the type after ?. Otherwise, it chooses the type after :.
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<42>; // false
type C = IsString<string>; // trueThe condition checks assignability. A string literal such as "hello" is assignable to string, so IsString<"hello"> becomes true.
Conditional types are useful for transforming a type based on its shape:
type ToArray<T> = T extends any[] ? T : T[];
type A = ToArray<string>; // string[]
type B = ToArray<number[]>; // number[]
type C = ToArray<boolean>; // boolean[]This example preserves an existing array but wraps other types in an array.
Conditional types distribute over unions
When a conditional type checks a plain type parameter, TypeScript applies it to each member of a union separately. This behavior is called distribution.
type ToArray<T> = T extends unknown ? T[] : never;
type Values = ToArray<string | number>;
// string[] | number[]TypeScript evaluates the type as if it were:
type Values = ToArray<string> | ToArray<number>;
// string[] | number[]This behavior is useful when processing each possible string separately. It can also produce larger unions than expected.
You can prevent distribution by wrapping both sides of the check in square brackets:
type ToArrayWithoutDistribution<T> =
[T] extends [unknown] ? T[] : never;
type Values = ToArrayWithoutDistribution<string | number>;
// (string | number)[]The first version creates a union of arrays. The second version creates one array whose elements may be strings or numbers.
`infer` captures a type part
Inside the true branch of a conditional type, infer declares a temporary type variable. TypeScript fills in that variable when it successfully matches the checked type.
type ElementType<T> =
T extends Array<infer Element> ? Element : never;
type A = ElementType<string[]>; // string
type B = ElementType<number[]>; // number
type C = ElementType<string>; // neverFor ElementType<string[]>, TypeScript matches string[] against Array<infer Element>. It infers Element as string.
never means that no valid result exists for that branch. Here, a non-array has no element type to extract.
You can use infer with function types too:
type ReturnTypeOf<T> =
T extends (...args: any[]) => infer Result ? Result : never;
type NameResult = ReturnTypeOf<() => string>; // string
type CountResult = ReturnTypeOf<(value: string) => number>; // numberThe pattern (...args: any[]) => infer Result matches a function with any parameters and captures its return type.
Matching strings with `infer`
A template literal type can appear in the condition. This lets you match a string type and capture a substring.
type RemovePrefix<T> =
T extends `id-${infer Value}` ? Value : never;
type A = RemovePrefix<"id-42">; // "42"
type B = RemovePrefix<"id-user">; // "user"
type C = RemovePrefix<"user-42">; // neverThe pattern requires the string to begin with id-. The infer Value part captures everything after that prefix.
You can capture more than one part:
type ParsePair<T> =
T extends `${infer Key}=${infer Value}`
? [Key, Value]
: never;
type Pair = ParsePair<"mode=dark">;
// ["mode", "dark"]The conditional type succeeds only when the input contains =. The two inferred variables receive the text on either side.
A delimiter can occur more than once. In that case, inference behavior depends on the pattern and can be less obvious. For predictable parsing, match one delimiter at a time and use a recursive type when the input contains a list of parts.
How this supports later patterns
Conditional types provide the decision:
type HasPrefix<T> =
T extends `api-${string}` ? true : false;infer provides the extraction:
type ApiName<T> =
T extends `api-${infer Name}` ? Name : never;Together, they turn a string type into structured type information. The same approach can extract route parameters, split delimited strings, or validate naming conventions.
Exercise
What is the resulting type of type Result = ParsePair<"theme=dark"> when ParsePair<T> matches ${infer Key}=${infer Value} and returns [Key, Value]?
Show answer
["theme", "dark"].