JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstypescript
Next
typescript
senior
conditional-types

How do conditional types work in TypeScript?

conditional-types
infer
type-level-programming
advanced
Quick Answer

Conditional types select types based on conditions using the syntax T extends U ? X : Y. They enable type-level programming, allowing different types based on input. Combined with infer, they can extract and transform types dynamically.

Detailed Explanation

Conditional Type Syntax:

  • T extends U ? X : Y
  • If T is assignable to U, type is X, otherwise Y
  • Distributive over unions by default

The 'infer' Keyword:

  • Declares type variable within condition
  • Extracts types from complex structures
  • Used in many utility types (ReturnType, etc.)

Use Cases:

  • Type extraction (unwrapping, getting properties)
  • Type transformation (mapping types)
  • Type filtering (exclude/extract)
  • Building complex utility types

Code Examples

Basic conditional types
// Simple conditional type
type IsString<T> = T extends string ? true : false;

type A = IsString<string>;  // true
type B = IsString<number>;  // false
type C = IsString<'hello'>; // true (literal extends string)

// Conditional with multiple checks
type TypeName<T> = 
  T extends string ? 'string' :
  T extends number ? 'number' :
  T extends boolean ? 'boolean' :
  T extends undefined ? 'undefined' :
  T extends Function ? 'function' :
  'object';

type T1 = TypeName<string>;     // 'string'
type T2 = TypeName<() => void>; // 'function'
type T3 = TypeName<string[]>;   // 'object'

// Distributive behavior with unions
type Stringify<T> = T extends any ? `${T & string}` : never;
type Result = Stringify<'a' | 'b' | 'c'>;
// 'a' | 'b' | 'c' - distributed over each member

Resources

TypeScript - Conditional Types

docs

Related Questions

How do mapped types work in TypeScript?

senior
mapped-types

What are template literal types and how do you use them?

senior
template-literal-types
Next
How do mapped types work in TypeScript?