A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/typescript/typescript-conditional-types/ below:

TypeScript Conditional Types - GeeksforGeeks

TypeScript Conditional Types

Last Updated : 24 Jan, 2025

In TypeScript, conditional types enable developers to create types that depend on a condition, allowing for more dynamic and flexible type definitions.

JavaScript
type IsString<T> = T extends string ? 'Yes' : 'No';

type Test1 = IsString<string>;
type Test2 = IsString<number>;

console.log('Test1:', 'Yes');
console.log('Test2:', 'No');

Output:

Test1: Yes
Test2: No
JavaScript
type Num<T> = T extends number[] ? number 
    : (T extends string[] ? string : never)
    
// Return num
const num: Num<number[]> = 4;

// Return invalid
const stringnum: Num<number> = "7";

console.log(num, stringnum);
Conditional Type Constraints

Conditional type constraints allow defining constraints on generic types within conditional types, enabling dynamic and precise type handling.

JavaScript
type CheckNum<T> = T extends number ? T : never;

type NumbersOnly<T extends any[]> = {
  [K in keyof T]: CheckNum<T[K]>;
};

const num: NumbersOnly<[4, 5, 6, 8]> = [4, 5, 6, 8];
const invalid: NumbersOnly<[4, 6, "7"]> = [4, 6, "7"];

Output:

Type '"7"' is not assignable to type 'never'.
Inferring Within Conditional Types

This feature extracts and utilizes types within a conditional type definition, enabling precise transformations.

JavaScript
type ElementType<T> = T extends (infer U)[] ? U : never;

const numbers: number[] = [1, 2, 3];
const element: ElementType<typeof numbers> = numbers[0];
const invalidElement: ElementType<typeof numbers> = "string";

Output:

Type 'string' is not assignable to type 'number'.
Distributive Conditional Types

These types distribute over unions, applying conditional logic to each union member individually.

JavaScript
type Colors = 'red' | 'blue' | 'green';

type ColorClassMap = {
  red: 'danger';
  blue: 'primary';
  green: 'success';
};

type MapColorsToClasses<T extends string> = T extends keyof ColorClassMap
  ? { [K in T]: ColorClassMap[T] }
  : never;

const redClass: MapColorsToClasses<Colors> = { red: 'danger' };
const invalidClass: MapColorsToClasses<Colors> = { yellow: 'warning' };

Output:

Type '{ yellow: "warning"; }' is not assignable to type 'never'.
Best Practices of Using TypeScript Conditional Types

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4