0
0
Typescriptprogramming~20 mins

Distributive conditional types in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Distributive Conditional Types Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
A1 | 0
B0
C1
D"1" | 0
Attempts:
2 left
💡 Hint
Remember that conditional types distribute over unions by default.
🧠 Conceptual
intermediate
2: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>;
Astring
Bnumber | string | boolean
Cnever
Dstring | never
Attempts:
2 left
💡 Hint
Conditional types remove members that don't satisfy the condition by turning them into 'never'.
🔧 Debug
advanced
2: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;
Astring
Bstring & number
Cnumber
Dstring | number
Attempts:
2 left
💡 Hint
Conditional types distribute only when the checked type is a naked type parameter.
📝 Syntax
advanced
2: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?
Atype ExtractString<T> = T extends string & number ? T : never;
Btype ExtractString<T> = T extends (string | number) ? string : never;
Ctype ExtractString<T> = T extends string | never ? T : never;
Dtype ExtractString<T> = T extends string ? T : never;
Attempts:
2 left
💡 Hint
Distributive conditional types work when the checked type is a naked type parameter.
🚀 Application
expert
2: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>;
A3
B1
C2
D0
Attempts:
2 left
💡 Hint
Remember that conditional types distribute over unions and 'keyof' returns keys of each member.