Advanced Generics 9 exercises
Problem

Spotting Missing Generics

In this exercise, we have a function called getValue which is mimicking a property access in TypeScript.

An object called obj is passed as the first argument and the key is keyof obj.

We should be getting back a number if we pass in a, a string if we pass in b, and a boolean if w

Loading exercise

Transcript

0:00 In this exercise, we have a function called getValue. What this is doing is basically mimicking a property access in TypeScript, where you basically have TObj, which is going to be the thing that's being passed in the first argument. Then the key is going to be keyof TObj there.

0:16 obj here, we've got a 1, b some-string, c 1. When we call getValue on it here, you can see it's being locked in here. What we should be getting back is if we pass in a, then we should be getting back a number. If we pass in b, should be getting back a string.

0:33 We're getting some really nice autocomplete, which indicates that this should be what's happening. Each of these, instead of being number, string, and boolean, are actually a union of number or string or boolean here, which is a little bit troublesome.

0:48 If I add something to this, if I add d is new Date here, then I do get d being offered to me in the autocomplete, but Date actually gets added to that union. It's almost like whatever we're getting back is a union of all of the values that are in the object.

1:06 Your job here is to try to fix this error, to try to improve this function so that it actually returns the specific value that we're getting instead of the general value or a union of all of the values. There's not going to be anything specific in here. Use your brain. Make sure you're thinking about how index access types work with unions and how keyof works. Good luck.