Implement conditional logic at the type level with TypeScript. Master conditional types and type constraints in this easy-level challenge on TypeScriptPro.
Bring conditional logic to TypeScript's type system! 🤔
In this easy-level challenge, you'll implement a utility type If<C, T, F> that works like a ternary operator at the type level. Based on a boolean condition C, it returns either the truthy type T or the falsy type F. This is a fundamental building block for creating dynamic, conditional types.
You'll learn how conditional types work with boolean literals and how TypeScript's type system handles boolean union types, providing insights into type-level branching logic.
Implement the util type If<C, T, F> which accepts condition C, a truthy value T, and a falsy value F. C is expected to be either true or false while T and F can be any type.
For example:
type A = If<true, 'a', 'b'> // expected to be 'a'
type B = If<false, 'a', 'b'> // expected to be 'b'Change the following code to make the test cases pass (no type check errors).
The If utility type uses TypeScript's conditional types to implement branching logic.
type If<C extends boolean, T, F> = C extends true ? T : FKey insights:
C extends boolean constrains C to boolean valuestrue, return Tfalse, return Fboolean (union of true | false), the conditional distributes, returning T | FThis simple pattern enables powerful type-level conditionals and is used extensively in complex type utilities to make decisions based on type information.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount