Advanced Generics 9 exercises
Problem

Generics with Conditional Types

For this exercise, we have a function called youSayGoodbyeISayHello where you pass in a greeting.

If the greeting is "goodbye", we return "hello", otherwise we return "goodbye":


function youSayGoodbyeISayHello(greeting: unknown) {
return greeting === "goodbye" ? "hello"

Loading exercise

Transcript

0:00 For this exercise, we have a function called youSayGoodbye and ISayHello. We're passing in a greeting here. If the greeting is goodbye, we return hello. Otherwise, we return goodbye.

0:10 This all appears to work on the runtime level, but actually, it's not working on the type level. We're expecting result here to be goodbye because we're passing in hello, but we're getting a union type of goodbye or hello. That's interesting. Same is true in the reverse, of course.

0:27 We probably know that we're going to need to add a type argument to this function. We're probably also going to need to use a conditional type as well.

0:36 I'll give you a clue to the solution here, which is the solution uses something unexpected and something that you may feel is a little bit illegal or a little bit troublesome or, "Maybe I shouldn't be using this in the solution." The solution will feel hacky. That's the way of saying it.

0:54 Good luck. Your job here is to try to get this working on the type level as well as the runtime level.