Lesson 12 of 56 · Typescript
Conditional Types
Duration: 20 minutes
Conditional Types Syntax
type IsString<T> = T extends string ? true : false;
type Test1 = IsString<number>; // false
type Test2 = IsString<"hello">; // true
Distributive Conditional Types
When the checked type is a union, the conditional distributes over each member.
type ToArray<T> = T extends any ? T[] : never;
type Arr = ToArray<string | number>; // (string[] | number[])
infer Keyword – extracting types
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type Func = (x: number) => boolean;
type R = ReturnType<Func>; // boolean
Practical Example – DeepPartial
type DeepPartial<T> = {
[K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];
};