0
0
Typescriptprogramming~5 mins

Distributive conditional types in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What are distributive conditional types in TypeScript?
Distributive conditional types automatically apply a conditional type to each member of a union type separately, then combine the results back into a union.
Click to reveal answer
beginner
How does TypeScript distribute conditional types over unions?
If a conditional type checks a generic type that is a union, TypeScript applies the condition to each union member individually, then unions the results.
Click to reveal answer
beginner
Given <br>type Example<T> = T extends string ? "yes" : "no";<br>What is Example<string | number>?
"yes" | "no" because the conditional type is applied separately to string and number and results are combined.
Click to reveal answer
intermediate
How can you prevent distributive behavior in conditional types?
Wrap the generic type in a tuple like [T] extends [U] ? X : Y to stop distribution over unions.
Click to reveal answer
intermediate
Why are distributive conditional types useful?
They let you write flexible types that automatically handle each union member, making type transformations easier and more powerful.
Click to reveal answer
What happens when a conditional type is applied to a union type in TypeScript?
AThe conditional type is applied to each union member separately.
BThe conditional type is ignored.
CThe conditional type applies only to the first union member.
DThe conditional type applies only if the union has one member.
How do you stop a conditional type from distributing over a union?
AUse the 'unknown' type.
BUse the 'never' type.
CUse the 'any' type.
DWrap the type in a tuple like [T].
What is the result of type R = (string | number) extends string ? true : false;?
Afalse
Btrue
Cstring | number
Dnever
Given type T<T> = T extends number ? 'num' : 'not num';, what is T?
A'not num'
B'num'
C'num' | 'not num'
Dstring | number
Which of these is a key feature of distributive conditional types?
AThey convert types to strings.
BThey automatically apply conditions to each union member.
CThey only work with arrays.
DThey prevent type inference.
Explain what distributive conditional types are and how they work with union types in TypeScript.
Think about how a condition checks each part of a union separately.
You got /4 concepts.
    Describe a method to prevent a conditional type from distributing over a union type and why you might want to do that.
    Consider how wrapping changes the type shape.
    You got /4 concepts.