Yuzhe's Blog

yuzhes

0268 · If

Posted at # TypeScript # TypeChallenge # TC-Easy
EN ·

0268 · If

Challenge Link

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 : F

Explanation

This is the type-level version of:

condition ? whenTrue : whenFalse

Step by Step

  1. C extends boolean constrains the condition so it must be true or false.
  2. C extends true ? T : F checks whether C is exactly true.
  3. If it is, the result is T.
  4. 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 : B

In 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 : string

So the final result is number.

For the false branch:

type Result = If<false, number, string>

This becomes:

false extends true ? number : string

So the result is string.

Alternative Solutions

Option 1: Reverse the Condition

type If2<C extends boolean, T, F> = C extends false ? F : T

This 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:

many later type-challenges become much easier. If is the smallest possible example of type-level branching.

Key Takeaways

Key concepts: