Tutorial hero
Lesson icon

Typing Untyped APIs with keyof

Originally published July 26, 2023 Time 2 mins

A little while ago I had a ​tip​ about using the keyof operator to add types to an otherwise untyped API. The example I showed used an example of creating types for some data that would be stored in localStorage:

StorageData interface

and then using keyof to wrap the localStorage API so that we can both ensure only data we expect is sent to localStorage, and we also know the type of data we can expect back from it:

StorageKey

Typed get method

You can check out the previous tip for a bit more detail about what is going on here, but the main point of this tip is that it could be better.

If we were to request a specific key from this get method - destinations for example - the typing information won’t tell us that it is specifically of the Destinations type.

TypeScript will think it could be any of the types specified in StorageData.

On one of my recent videos, a comment from TheAUa led me to a much better solution:

Typed get method improved

The typing information is a bit more complex now, but now since we are using a generic T for the key passed in, we can give the data we are accessing from storage it’s specific type by utilising this T value and selecting it from the StorageData type.

So, if I access the destinations key, TypeScript will know that it is of the type Destinations specifically now.

Learn to build modern Angular apps with my course