TypeScript Type Challenge If Walkthrough
The goal of this challenge is to implement a generic If type which accepts condition C, a truthy return type T, and a falsy return type F. C is expected to be either true or false while T and F can be any type.
The challenge: https://github.com/type-challenges/type-challenges/blob/main/questions/00268-easy-if/README.md
Watch the video
Coming soon
An example case
For example, given the following cases, our If type should return the type shown in the comments:
If<true, 'a', 'b'> // 'a'
If<false, 'a', 2> // 2
Approach
In plain english, we want our type to:
if C is true, return T, if C is false, return F
This is the textbook use-case for conditional types in TypeScript
The solution
We'll start by implementing a conditional type that returns T or F based on the value of C:
type If<C, T, F> = C extends true ? T : F
If C is assignable to true, return F, otherwise return F.
This is almost the complete solution, but at the moment our C
generic can take on any value, we want to constrain it to only accept boolean values. The final solution is:
type If<C extends boolean, T, F> = C extends true ? T : F