Skip to lesson

TypeScript · Lesson 29 of 42

Conditional types and infer

Choose a type with T extends U ? X : Y, see how it distributes over unions, and extract inner types such as array elements and promise results with infer.

Beginner to advanced·16 min·Advanced types·Updated 2026-11-24

UNDERSTAND IT. THEN TRY IT.

What you can do after this lesson

You will be able to write types that make decisions, the way if makes decisions in code, and to pull pieces out of other types. This is the most advanced idea in the course so far, and it powers many of the utility types you already use. Take it slowly and read the examples twice.

The conditional type

A conditional type looks like the ternary operator, but works on types. It uses extends to ask: "is T assignable to U?"

typescript
type IsString<T> = T extends string ? true : false;

const a: IsString<"hello"> = true;
const b: IsString<42> = false;
console.log(a, b);
result
true false

If T is a string, the type is true; otherwise it is false. The compiler evaluates this at compile time, and the types vanish at run time. You can check the result by trying a wrong assignment, which reveals what the type is:

typescript
type IsString<T> = T extends string ? true : false;

const wrong: IsString<42> = true;
result
example.ts(3,7): error TS2322: Type 'true' is not assignable to type 'false'.

A more practical example: a function whose return type depends on its argument type.

typescript
type Name<T> = T extends number ? string : number;

function convert<T extends string | number>(value: T): Name<T> {
  return (typeof value === "number" ? String(value) : Number(value)) as Name<T>;
}

const asText = convert(42);
const asNumber = convert("17");
console.log(asText.padStart(4, "0"), asNumber + 1);
result
0042 18

Notice the assertion inside convert. The compiler cannot prove that the branches match a conditional return type, so a cast is the usual price; this is one of the few places where an assertion is normal, because the signature, not the body, is the contract.

Distribution over unions

When the checked type is a naked type parameter (just T, not [T] or T[]), a union is split, the conditional runs on each member, and the results are united:

typescript
type ToArray<T> = T extends unknown ? T[] : never;

const x: ToArray<string | number> = ["a"];
const y: ToArray<string | number> = [1];
console.log(x, y);
result
[ 'a' ] [ 1 ]

ToArray<string | number> is string[] | number[], not (string | number)[]. Distribution is the behaviour behind Exclude and Extract, which are conditional types:

typescript
type MyExclude<T, U> = T extends U ? never : T;

type Letters = "a" | "b" | "c";
type WithoutA = MyExclude<Letters, "a">;

const letter: WithoutA = "b";
console.log(letter);
result
b

For each member of Letters, if it extends "a" it becomes never (which disappears from a union), otherwise it stays. To turn distribution off, wrap both sides in square brackets: [T] extends [U] ? ... : ....

infer: capturing a piece

Inside the extends part of a conditional type, you can write infer Name to ask the compiler to work out a type and give it a name. This extracts the element type of an array:

typescript
type ElementOf<T> = T extends (infer U)[] ? U : T;

const a: ElementOf<string[]> = "text";
const b: ElementOf<number[]> = 5;
const c: ElementOf<boolean> = true;
console.log(a, b, c);
result
text 5 true

Read it as: "if T is an array of something, call that something U and give me U; otherwise give me T unchanged". Here is a hand-written ReturnType:

typescript
type MyReturnType<F> = F extends (...args: never[]) => infer R ? R : never;

function makeUser() {
  return { name: "Asha", age: 30 };
}

type User = MyReturnType<typeof makeUser>;
const user: User = { name: "Ben", age: 25 };
console.log(user);
result
{ name: 'Ben', age: 25 }

And a version that unwraps a promise, which is how Awaited is built:

typescript
type Unwrap<T> = T extends Promise<infer V> ? V : T;

const a: Unwrap<Promise<string>> = "done";
const b: Unwrap<number> = 7;
console.log(a, b);
result
done 7

A practical use

Conditional types and mapped types combine well. This picks out the keys of an object whose values are functions:

typescript
type MethodNames<T> = {
  [K in keyof T]: T[K] extends (...args: never[]) => unknown ? K : never;
}[keyof T];

type Counter = { value: number; increment(): void; reset(): void };
type Names = MethodNames<Counter>;

const method: Names = "increment";
console.log(method);
result
increment

The trailing [keyof T] indexes the mapped type to collect its values into a union, dropping the nevers. This is a pattern worth recognising even if you do not write it often.

When to stop

Conditional types are powerful and easy to overuse. Types that take a long time to read are a cost for everyone who maintains the code. A good test: if a simple function overload, a union or a utility type does the job, use that. Save conditional types for libraries and for places where the alternative is repeating many near-identical types.

Common mistakes

Expecting runtime behaviour. A conditional type is resolved at compile time. It cannot look at an actual value.

Forgetting distribution. A naked T splits a union. If you need the union treated as a whole, wrap it in brackets.

Writing infer outside extends. infer is only allowed in the extends clause of a conditional type.

Overcomplicating. If two readers disagree about what a type means, rewrite it.

Exercise

Write IsArray<T> returning true or false, and test it with string, number[] and string | string[], noticing the distribution. Write FirstArg<F> that gets the type of a function's first parameter using infer. Write NonFunctionKeys<T>, the opposite of MethodNames, and test it on an object type with both data and methods.

Next: Template literal types.

KNOWLEDGE CHECK

A quick check. You’ve got this.

Try each question. Every answer comes with an explanation.

0 / 4 understood
01 What does string extends number ? "yes" : "no" evaluate to?
02 What does the conditional type IsArray<T> = T extends unknown[] ? true : false give for string | number[] when written with a naked T?
03 What does infer U do in T extends (infer U)[] ? U : T?
04 Which utility type is a conditional type using infer?

Ready for the next small win?

Mark the lesson complete when you are ready.

Course navigation

Frontend

TypeScript tutorial

Add types to JavaScript to catch mistakes before your code runs, from your first annotation to generics and real projects.

Your progress 0/42
Learning something new?Explore all courses