...

/

Conditional Types and infer

Conditional Types and infer

Use conditional types and infer to create powerful, reactive type logic that adapts to your code.

We’ve seen how TypeScript can transform types with tools like template literals and mapped types. But now we’re entering a more advanced stage where types can make decisions, extract values, and react conditionally.

This is where conditional types and the infer keyword come into play. They form the core of TypeScript’s type-level logic system. With them, we’re not just defining types—we’re programming with types.

By the end of this lesson, we’ll be able to model advanced transformations, extract inner types, and create utility types comparable to those in TypeScript’s standard library.

Conditional types: Types that make decisions

Sometimes we want types that behave differently depending on their input—types that can ask questions and respond with different shapes or values. That’s exactly what conditional types let us do.

Here’s the basic structure:

T extends U ? X : Y

It looks like a ternary (cond ? ifTrue : ifFalse) and it is. But instead of branching at runtime, it does it at the type level. If T extends U, then we resolve to X; otherwise, we resolve to Y.

This gives us the ability to build types that adapt based on relationships between other types. Let’s see it in action.

Press + to interact
TypeScript 5.8.3
Files
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false

Explanation:

  • Line 1: IsString<T> checks whether T extends string. If so, it returns true; otherwise, it returns false.

  • Line 3: IsString<string> resolves to true.

  • Line 4: IsString<number> resolves to false.

This may seem like a simple example, but it's the same logic behind utility types like NonNullable, ReturnType, and Extract.

Making types smarter with infer

We’ve just seen how conditional types allow us to branch and choose types based on conditions. But there’s one more tool that unlocks next-level flexibility: the infer keyword. ...

Access this course and 1400+ top-rated courses and projects.