typescript-book icon indicating copy to clipboard operation
typescript-book copied to clipboard

Conditional Types

Open basarat opened this issue 7 years ago • 3 comments

Yay : https://github.com/Microsoft/TypeScript/pull/21316

This is much better and simpler than mapped types 🌹

basarat avatar Jan 21 '18 23:01 basarat

infer keyword : https://github.com/Microsoft/TypeScript/pull/21496

basarat avatar Jul 02 '19 23:07 basarat

A lovely example of what is possible (mapping arrays to booleans): Combing mapped and conditional types https://twitter.com/wroctypescript/status/1145669408003710984?s=11

image

basarat avatar Jul 02 '19 23:07 basarat

Using conditional types to infer the members of a tuple array

type GetArrayMembers<T> = T extends {[index in keyof T]: infer V} ? V : never;
const example = [1,2,4] as const;
type Members = GetArrayMembers<typeof example>; // 1 | 2 | 4

Simpler :

const element = [1,2,4] as const;
type Members = typeof element[number]; // 1 | 2 | 4;

basarat avatar Jul 02 '19 23:07 basarat