Classes 9 exercises
Problem

Create a Type Safe Map with the Builder Pattern

For this exercise, you'll be implementing a little piece of a builder pattern class.

Here is a TypeSafeStringMap class:


class TypeSafeStringMap<TMap extends Record<string, string> = {}> {
private map: TMap;
constructor() {
this.map = {} as TMap;
}
get(key: keyof TMap):

Loading exercise

Transcript

0:00 In this exercise, I'm going to get you to implement a little piece of a build-a-pattern class. This is a type-safe string map. It's pretty similar to the tuple we had before except it's a record instead of a tuple. We have a map here where we're building it up by setting Matt Pocock, Jools Holland, and Brandi Carlisle.

0:20 We only really care about the keys here. Currently, all of the values are going to be strings. We only care about the keys because that's what we're going to use to type our get function. Our get function here currently doesn't look like it's working terribly well because map is currently typed as any.

0:41 That's because our set function is typed as unknown, the return type here. Your job is to work out what the type for this should be knowing that we have this TMapGeneric up here that we're slowly trying to build up and add more types to. We should be able to get autocomplete inside this area here.

1:02 This should be throwing an error. I should be able to return string each time I do a get. Good luck.