0
0
Typescriptprogramming~5 mins

Conditional type with generics in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a conditional type in TypeScript?
A conditional type chooses one type or another based on a condition. It uses syntax like T extends U ? X : Y, meaning if T fits U, use X, else use Y.
Click to reveal answer
beginner
How do generics work with conditional types?
Generics let you write flexible types that depend on input types. When combined with conditional types, you can create types that change based on the generic type passed in.
Click to reveal answer
beginner
Explain this TypeScript type: type IsString<T> = T extends string ? true : false;
This type checks if T is a string. If yes, it becomes true, otherwise false. For example, IsString<string> is true, but IsString<number> is false.
Click to reveal answer
intermediate
What happens if you use a union type with a conditional type?
Conditional types distribute over union types. For example, IsString<string | number> becomes IsString<string> | IsString<number>, which is true | false.
Click to reveal answer
beginner
Why use conditional types with generics?
They let you create smart types that adapt based on input types. This helps catch errors early and makes your code more flexible and clear.
Click to reveal answer
What does this conditional type do? type Check<T> = T extends number ? 'Number' : 'Other';
AReturns 'Number' if T is number, else 'Other'
BAlways returns 'Number'
CAlways returns 'Other'
DThrows an error
What is the result of Check<string> if Check<T> = T extends number ? 'Number' : 'Other'?
A'Number'
Bnumber
Cstring
D'Other'
How do conditional types behave with union types like T = string | number?
AThey apply to the whole union as one type
BThey ignore union types
CThey distribute over each union member separately
DThey cause a syntax error
Which syntax correctly defines a conditional type?
A<code>if T then X else Y</code>
B<code>T extends U ? X : Y</code>
C<code>switch(T) { case U: X; default: Y; }</code>
D<code>type T = X | Y;</code>
What is the benefit of using conditional types with generics?
AThey make types flexible and adaptive
BThey slow down compilation
CThey remove type safety
DThey are only for runtime checks
Explain how conditional types work with generics in TypeScript.
Think about how you can check if a generic type fits another type and return different types.
You got /4 concepts.
    Describe what happens when a conditional type is used with a union type generic.
    Remember how unions split the conditional check for each type inside.
    You got /3 concepts.