0
0
Typescriptprogramming~5 mins

Conditional type syntax in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the basic syntax of a conditional type in TypeScript?
A conditional type uses the syntax: <br>T extends U ? X : Y<br>It means if type T can be assigned to type U, then the type is X, otherwise it is Y.
Click to reveal answer
beginner
Explain the role of extends in conditional types.
In conditional types, extends checks if one type can be assigned to another. It acts like a question: "Does T fit into U?" If yes, the true branch is chosen; if no, the false branch is chosen.
Click to reveal answer
beginner
What does this conditional type do?<br>type IsString<T> = T extends string ? true : false;
It checks if the type T is a string. If yes, it returns true, otherwise false. For example, IsString<'hello'> = true and IsString<42> = false.
Click to reveal answer
intermediate
Can conditional types be nested in TypeScript?
Yes, conditional types can be nested inside each other to create more complex type logic. For example:<br>type Nested<T> = T extends string ? (T extends 'hello' ? true : false) : false;
Click to reveal answer
intermediate
What happens if the condition in a conditional type is distributive?
If the type T is a union, the conditional type is applied to each member separately, then results are combined. This is called distributive conditional types.
Click to reveal answer
What does this conditional type return?<br>type Check<T> = T extends number ? 'Yes' : 'No';<br>What is Check<string>?
Anumber
B'Yes'
Cstring
D'No'
In T extends U ? X : Y, what happens if T is a union type?
AThe conditional type applies to each member of the union separately
BThe conditional type fails to compile
CThe conditional type ignores the union and treats it as one type
DThe conditional type always returns Y
What keyword is used to check type compatibility in conditional types?
Aextends
Bimplements
Cis
Dtypeof
Which of these is a valid conditional type?
Atype T = if (T extends U) X else Y;
Btype T = string ? number : boolean;
Ctype T = T extends U ? X : Y;
Dtype T = T is U ? X : Y;
What is the result of this type?<br>type Result = 'a' | 'b' extends string ? true : false;
Afalse
Btrue
C'a' | 'b'
Dstring
Explain how conditional types work in TypeScript and give a simple example.
Think of it like an if-else for types.
You got /3 concepts.
    Describe what distributive conditional types are and why they are useful.
    Consider how a condition applies to multiple types inside a union.
    You got /3 concepts.