0
0
Typescriptprogramming~10 mins

Conditional type syntax in Typescript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Conditional type syntax
Start with Type T
Check Condition: T extends U?
Yes No
Use Type X
Result Type
The conditional type checks if type T fits type U. If yes, it uses type X; if no, it uses type Y.
Execution Sample
Typescript
type IsString<T> = T extends string ? "Yes" : "No";
type Test1 = IsString<string>;
type Test2 = IsString<number>;
Defines a conditional type that returns "Yes" if T is string, otherwise "No".
Execution Table
StepType TCondition (T extends string?)Result Type
1stringYes"Yes"
2numberNo"No"
💡 All types tested, conditional type resolved to final result types.
Variable Tracker
VariableStartAfter 1After 2Final
Tgenericstringnumbernumber
Result Typeunknown"Yes""No""No"
Key Moments - 2 Insights
Why does Test1 become "Yes" but Test2 becomes "No"?
Because in execution_table row 1, T is string which matches the condition, so it returns "Yes"; in row 2, T is number which does not match, so it returns "No".
Is the condition checked at runtime or compile time?
The condition is checked at compile time by TypeScript's type system, not at runtime, as shown by the static evaluation in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result type when T is string?
A"No"
B"Yes"
Cstring
Dnumber
💡 Hint
Check execution_table row 1 under Result Type column.
At which step does the condition T extends string evaluate to false?
AStep 1
BNo step, always true
CStep 2
DBoth steps
💡 Hint
Look at execution_table Condition column for Step 2.
If we change the condition to T extends number, what would Test1 result be?
A"No"
Bstring
C"Yes"
Dnumber
💡 Hint
Refer to how condition affects result in execution_table and variable_tracker.
Concept Snapshot
Conditional types syntax:
type Result = T extends U ? X : Y;
Checks if T fits U.
If yes, Result is X.
If no, Result is Y.
Used for type decisions at compile time.
Full Transcript
This visual trace shows how TypeScript conditional types work. We start with a generic type T. The condition checks if T extends another type U, here string. If true, it returns one type, else another. We see examples with T as string and number. The condition is evaluated at compile time, not runtime. The result type changes accordingly. This helps create flexible types based on conditions.