0268 · If
0268 · If
Problem
Implement a type If<C, T, F> that works like the ternary operator at the type level.
type A = If<true, "yes", "no"> // "yes"
type B = If<false, "yes", "no"> // "no"The challenge is small, but it is a clean introduction to conditional types.
Solution
type If<C extends boolean, T, F> = C extends true ? T : FExplanation
This is the type-level version of:
condition ? whenTrue : whenFalseStep by Step
C extends booleanconstrains the condition so it must betrueorfalse.C extends true ? T : Fchecks whetherCis exactlytrue.- If it is, the result is
T. - Otherwise, the result is
F.
Why Check extends true?
At the type level, we cannot write a normal runtime if statement. Instead, we express branching with a conditional type:
SomeType extends OtherType ? A : BIn this challenge, C is the condition, so C extends true is the natural way to ask "is the condition true?"
Example Walkthrough
type Result = If<true, number, string>This becomes:
true extends true ? number : stringSo the final result is number.
For the false branch:
type Result = If<false, number, string>This becomes:
false extends true ? number : stringSo the result is string.
Alternative Solutions
Option 1: Reverse the Condition
type If2<C extends boolean, T, F> = C extends false ? F : TThis is logically equivalent. Some people find it slightly less direct because the "true" branch appears second, but it works the same way.
Option 2: Tuple Lookup Trick
type If3<C extends boolean, T, F> = [F, T][C extends true ? 1 : 0]This also works, but it is less readable than the plain conditional type. For a beginner challenge, the direct version is better.
Thought Process
The key realization is that this problem is not really about booleans. It is about learning the syntax of conditional types.
Once you see the shape:
Condition extends X ? A : B
many later type-challenges become much easier. If is the smallest possible example of type-level branching.
Key Takeaways
- Conditional types are the type-system equivalent of ternary expressions.
C extends booleankeeps the input aligned with the problem constraints.- For simple branching problems, the most direct solution is usually the best one.
Key concepts:
- Conditional Types
- Type-level branching with
extends ? :
