typescript

Conditional Types

Create types that depend on conditions using extends

Tarun Sharma
Tarun SharmaJanuary 15, 2024 · 1 min read · Last Updated:

Basic Conditional

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

type A = IsString<'hello'>; // true
type B = IsString<42>; // false

Extract and Exclude

type EventType = 'click' | 'scroll' | 'mousemove';

// Built-in Extract
type MouseEvents = Extract<EventType, 'click' | 'mousemove'>;
// "click" | "mousemove"

// Built-in Exclude
type NonClickEvents = Exclude<EventType, 'click'>;
// "scroll" | "mousemove"

Infer Keyword

// Extract return type
type ReturnOf<T> = T extends (...args: any[]) => infer R ? R : never;

const fn = () => ({ id: 1, name: 'test' });
type Result = ReturnOf<typeof fn>; // { id: number; name: string }

// Extract array element type
type ArrayElement<T> = T extends (infer E)[] ? E : never;
type Item = ArrayElement<string[]>; // string

// Extract Promise value
type Awaited<T> = T extends Promise<infer V> ? V : T;
type Value = Awaited<Promise<number>>; // number

Function Parameter Types

type FirstParam<T> = T extends (first: infer F, ...args: any[]) => any ? F : never;

type Params = FirstParam<(name: string, age: number) => void>; // string

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Tarun Sharma

Written byTarun Sharma
Full-stack developer and tech educator with 10+ years of experience building scalable applications. Passionate about Node.js, NestJS, React, and cloud technologies. Creator of 50+ courses on Udemy and active YouTube educator helping developers level up their skills.
Connect

Is this page helpful?

Related VideosView All

Stack Overflow Clone - APIs Integration Redux Toolkit [Closure] - App Demo #05

Become Ninja Developer - API security Best Practices with Node JS Packages #15

Nest JS Microservices using HTTP Gateway and Redis Services (DEMO) #nestjs #microservices #16