Challenge - 5 Problems
Distributive Conditional Types Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple distributive conditional type
What is the type of
Result after the following code runs?Typescript
type A = "x" | "y" | "z"; type Result = A extends "x" ? 1 : 0;
Attempts:
2 left
💡 Hint
Remember that conditional types distribute over unions by default.
✗ Incorrect
The conditional type distributes over each member of the union 'A'. For 'x' it returns 1, for 'y' and 'z' it returns 0, so the union is 1 | 0.
🧠 Conceptual
intermediate2:00remaining
Understanding distribution with 'never'
What is the resulting type of
Filtered in this code?Typescript
type Filter<T> = T extends string ? T : never;
type Filtered = Filter<number | string | boolean>;Attempts:
2 left
💡 Hint
Conditional types remove members that don't satisfy the condition by turning them into 'never'.
✗ Incorrect
The conditional type distributes over the union. Only 'string' satisfies the condition, others become 'never'. The union of 'string | never' simplifies to 'string'.
🔧 Debug
advanced2:00remaining
Why does this distributive conditional type not behave as expected?
Consider this code snippet. What is the type of
Result and why might it be unexpected?Typescript
type Wrap<T> = (arg: T) => void; type Result = Wrap<string> | Wrap<number> extends (arg: infer U) => void ? U : never;
Attempts:
2 left
💡 Hint
Conditional types distribute only when the checked type is a naked type parameter.
✗ Incorrect
Here, 'Wrap | Wrap' is a union but the checked type is not a naked type parameter, so the conditional type does not distribute. The 'infer U' must work for the entire union, resulting in the intersection 'string & number', which is 'never' but shown as 'string & number'.
📝 Syntax
advanced2:00remaining
Which option correctly uses distributive conditional types to extract types?
Which of the following type definitions correctly extracts only the string types from a union?
Attempts:
2 left
💡 Hint
Distributive conditional types work when the checked type is a naked type parameter.
✗ Incorrect
Option D correctly uses a naked type parameter 'T' in the conditional type, so it distributes over unions and extracts string types. Other options either use incorrect conditions or impossible intersections.
🚀 Application
expert2:00remaining
Calculate the number of keys in a mapped distributive conditional type
Given the following code, how many keys does the type
Result have?Typescript
type Keys<T> = T extends any ? keyof T : never;
type Union = { a: number } | { b: string };
type Result = Keys<Union>;Attempts:
2 left
💡 Hint
Remember that conditional types distribute over unions and 'keyof' returns keys of each member.
✗ Incorrect
The conditional type distributes over the union. 'keyof {a:number}' is 'a', 'keyof {b:string}' is 'b'. The union of keys is 'a' | 'b', so there are 2 keys.