Beginner's TypeScript Tutorial (18 exercises)
Problem

Assigning Dynamic Keys to an Object

Consider this createCache function:

const createCache = () => {
  const cache = {};

  const add = (id: string, value: string) => {
    cache[id] = value;
  };

  const remove = (id: string) => {
    delete cache[id];
  };

  return {
    cache,
    add,
    remove,
  };
};

We've got an empty object that we're calling cache, and we're allowing users to specify add and remove on it.

Inside the tests we have some errors:

expect(cache.cache["123"]).toEqual("Matt")

Hovering over the errors makes it look like cache has been typed as an empty object.

There are also errors in the createCache function:

Expression of type 'string' can't be used to index type '{}'

There is no indexing happening with our current code..

Challenge

Your challenge is to reference the TypeScript docs and work out what could be causing this problem.

Update cache to be typed properly so the errors go away.

Transcript

Inside this createCache function, we're creating an object, which we're calling a cache, and allowing users to specify add and remove on that cache. Inside here, you can see we've got cache createCache add 123 Matt, and then there's some errors that are happening here because it looks like cache is just typed as this. It's like an empty object, which doesn't seem quite correct.

We're getting errors up here, too. "No index signature with a parameter of type string was found on type..." What? OK, some confusing stuff happening here and all to do with index signatures. We can't index it there. There's no indexing happening here.

Your job is to go into the TypeScript docs and work out what could be causing this problem and how we should type this line of code here to make these errors go away.