Function Overloads 8 exercises
Problem

The "Instantiated with Subtype" Error

In this exercise, we're going to tackle one of TypeScript's most difficult errors.

Here we have an object called obj, which contains a, b, and c with values of 1, 2, and 3, respectively.

The ObjKey type uses keyof and typeof to extract the keys, giving us "a" | "b" | "c".

Th

Loading exercise

Transcript

0:00 In this exercise, we're going to tackle one of TypeScript's gnarliest, weirdest errors. We have an object here called obj, and it's just a, b, c with 1, 2, 3 in them. We're extracting out the ObjKey here. We're getting a, b, or c locked into this type. We've got a function called getObjValue. Inside here, we've got TKey extends ObjKey.

0:23 If I were to remove this, then everything would be fine. We can see that calling getObjValue here, the key gets locked in as this type here, because we're passing in a and we have a in there. Inside here, it works with b and it works with c. The thing that we get back is the literal value from the object const up here, which is really nice.

0:50 What we want to do here is when we call getObjValue with nothing, we want it to default to a. We want to default it like this. This seems to not work because, what's happening here, type a is not assignable to type TKey. A is assignable to the constraint of type TKey, but TKey could be instantiated with a different subtype of constraint a, b, or c.

1:17 If you've seen this error before, bad luck, you're about to see it again here. I do want to give you a really good mental model, but I want you to struggle a bit first. I'll give you a clue, which is that function overloads are a really nice way to solve this error. I want you to look that there are two call signatures here. There's this one and there's this one.

1:43 That's all the clues I'm going to give you. I'll show you the solution in a minute. Good luck.