Classes 9 exercises
solution

Getters and Setters in the Builder Pattern

The set method is typed as unknown, which means that we can't call any methods on it.

Let's remove the unknown from set.


// removed the unknown from set
set<K extends string>(key: K, value: string) {
(this.map[key] as any) = value;
return this;
}

Now when we hover

Loading solution

Transcript

0:00 The fix here is to change the type of the set method. Before we had this unknown there. Now what this was doing is it's saying object was a type unknown so you can't call any stuff on it. Unknown is obviously wrong. What happens if we remove that? If we remove that we return this.

0:18 What we end up with is if we just remove this couple of things here, we end up with type-safe string map with an empty object. What this indicates to me is that the builder pattern isn't yet working because even though we're inferring the type of mat from here it's not being added to that record.

0:37 We need to add a return type on here. This is going to be type-safe string map. We need to pass in tmap first. This tmap then it means that you're going to end up with this record up here, which is defaulted to an empty object. We need to add this key with the value and intersect it in. We can do this -- we can do, "And Record<K string."

1:07 Now, again, we don't care about the value here. That's going to be string here. We get...Wow, look at that. Let me build that up. We've got, "Set Matt Pocock." That means we end up with a type-safe string map with Record map and string in. Then we say, "Set Jools Holland." Then we can hover over that and see that, "And Record Jools string." Finally, "Set Brandi Carlisle."

1:38 What that means we end up with the perfect type for what we need -- Record Matt string, Record Jools Holland, and Record Brandi Carlisle. We get autocomplete here, which is just absolutely magic because this map.get, it's doing key of tmap here. Without that, we wouldn't get any autocomplete. We wouldn't get these errors here.

1:59 You can start to get a sense for what's possible with the builder pattern that you can represent really anything you want to in here just by doing some type transformations. This pattern of returning this of doing a return type which adds something into the generic slot is extremely powerful.