Lesson 1 · Unit 03
Conditional Types
Types that ask a question, and infer the answer
What you practise
T extends U ? X : Y,inferto pull a type out, distribution over unions,ReturnTypeandAwaitedrebuilt
Try a question from this lesson
Pick one
A type can hold a question. Read line 2 as Python's "text" if ... else "other", with extends meaning "fits". What is B?
type Kind<T> =
T extends string ? "text" : "other";
type A = Kind<"hi">;
type B = Kind<number>;Correct answer
"other"
Why
T extends string asks "is T assignable to string?". number is not, so the false branch is taken: "other". Nothing is rejected: a conditional type asks a question, it does not impose a rule. Kind<"hi"> takes the true branch.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Conditional types
T extends U ? X : Y is a conditional type: if T is assignable to U the result is X, otherwise Y. It is Python's x if cond else y, evaluated by the compiler, on types.
On a fixed type it is pointless. Inside a generic it lets a result type depend on an input type, so a function can return different types for different arguments.
type Kind<T> =
T extends string ? "text" : "other";
type A = Kind<"hi">; // "text"
type B = Kind<boolean>; // "other"
const a: A = "text";
const b: B = "other";Concept
infer
infer declares a type variable inside the extends pattern, and the compiler fills it in by matching. T extends (infer E)[] reads: "is T an array of something? Call that something E."
It is destructuring for types, like [first, *rest] = xs pulling a piece out of a value. If the pattern does not match, the false branch is taken.
type Elem<T> =
T extends (infer E)[] ? E : never;
type A = Elem<string[]>; // string
type B = Elem<number[][]>; // number[]
const a: A = "x";
const b: B = [1, 2];Concept
Distribution
Hand a conditional type a union and it does not ask its question once. It asks it of each member separately and unions the answers. This is called distribution.
So a conditional type works as a filter: map the members you want to themselves and the rest to never, the empty union, which disappears. A list comprehension with an if, over a union.
type NoNull<T> =
T extends null | undefined ? never : T;
type A = NoNull<string | null>;
// string
const a: A = "x";
// const b: A = null; // rejected9 more exercises in the app
- 4× multiple choice
- 1× match the pairs
- 2× fill the blanks
- 1× type the answer
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.