0
0
Typescriptprogramming~5 mins

Non-distributive conditional types in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a distributive conditional type in TypeScript?
A distributive conditional type applies the condition separately to each member of a union type. For example, T extends U ? X : Y distributes over unions in T.
Click to reveal answer
intermediate
How can you prevent distribution in a conditional type?
Wrap the type in a tuple or another container, like [T] extends [U] ? X : Y. This stops TypeScript from distributing over union members.
Click to reveal answer
intermediate
Why would you want to use non-distributive conditional types?
To check a condition on the whole union type as one unit, not on each member separately. This helps when you want to treat the union as a single type.
Click to reveal answer
beginner
What does this TypeScript code do?<br>
type Example<T> = T extends string ? true : false;
If T is a union like 'a' | 1, it checks each member: 'a' extends string → true, 1 extends string → false. So the result is true | false.
Click to reveal answer
intermediate
How does this code behave differently?<br>
type Example<T> = [T] extends [string] ? true : false;
It checks if the whole T (even if a union) extends string as a whole. So 'a' | 1 does NOT extend string, result is false.
Click to reveal answer
What happens when you use a conditional type like T extends U ? X : Y with a union type T?
AThe condition is checked for each member of the union separately.
BThe condition is checked once for the whole union.
CThe type always resolves to Y.
DThe type always resolves to X.
How do you stop a conditional type from distributing over a union?
AUse the 'unknown' type.
BUse the 'never' type.
CWrap the type parameter in a tuple like [T].
DUse the 'any' type.
Given type T = 'a' | 1;, what is the result of T extends string ? true : false?
Anever
Btrue
Cfalse
Dtrue | false
Given type T = 'a' | 1;, what is the result of [T] extends [string] ? true : false?
Afalse
Btrue
Ctrue | false
Dnever
Why is non-distributive conditional type useful?
ATo split a union into individual types.
BTo check a condition on the entire union type as a whole.
CTo always return true.
DTo convert types to strings.
Explain what distributive conditional types are and how to make a conditional type non-distributive in TypeScript.
Think about how TypeScript treats unions inside conditional types.
You got /3 concepts.
    Describe a scenario where you would want to use a non-distributive conditional type instead of a distributive one.
    Consider when treating a union as a single type matters.
    You got /3 concepts.