📘

Conditional Types: Type-Level Logic

Advanced
130 XP
50 min
Lesson Content

Conditional Types

Conditional types allow you to create types that depend on other types, enabling powerful type-level programming.

Basic Conditional Types

type IsArray = T extends any[] ? true : false;

type Test1 = IsArray; // true
type Test2 = IsArray; // false

Infer Keyword

type ArrayElement = T extends (infer U)[] ? U : never;

type Element = ArrayElement; // string

Distributed Conditional Types

type ToArray = T extends any ? T[] : never;

type StrArrOrNumArr = ToArray; // string[] | number[]
Example Code

Understanding conditional type syntax

// Conditional types are compile-time only
// For practice, we'll simulate the concept

function checkType(value: any): string {
  if (Array.isArray(value)) {
    return "array";
  }
  return typeof value;
}

console.log(checkType([1, 2, 3]));
console.log(checkType("hello"));

Expected Output:

array
string
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code