TypeScript Generics Workshop (6 exercises)

Inference Inside Generic Functions

Here is a function remapPerson that takes in a key and a value for that key:

This problem has a dynamic key inside that is checked, and then the appropriate value returned.

Loading exercise


[0:00] In this problem, we have most of a function handled for us. We've got a remapPerson thing. What we're doing here is we're saying, "Key extends keyof Person." We're taking in the key and then we're taking in the value of that key.
[0:17] We can say, remapPerson, let's say, age and let's say, value 123123. This is then typed as a number there, which is pretty clever in itself. If we get birthdate here, then this is going to be a value: Date. But we're not interested in the usage of this. All we're interested in is solving this error, "Type 'Date' is not assignable to type 'Person[Key]'. Type 'Date' is not assignable to type 'never'."

[0:45] I'm intrigued by what you think of this. This isn't a real function, necessarily. It's not one that I would find in my app, but this problem of you have a dynamic key inside here. You're checking if the key is a certain value and then you return a certain value based on that. What it's saying is, "If key is birthdate, then ignore the value that the user passes in."

[1:09] I want you to try to find a solution to this error using purely only type level stuff. You're not going to be adding any runtime stuff here. Again, this is going to feel like a hack.

[1:21] Good luck.