Tutorial hero
Lesson icon

The keyof Operator

Originally published June 01, 2023 Time 2 mins

Accessing things like localStorage, or anything else that allows it, directly through an untyped string can be a bit iffy.

For example, let’s say I want to access the ratings from localStorage, there isn’t anything preventing a typo like:

localStorage.getItem('rating');

Which can easily cause runtime errors and debugging pain. Instead you can create a custom type to constrain what properties are available:

custom type to constrain

and then, to make your life easier, you can use the keyof operator:

keyof operator

to create a new type that will accept any of the properties from the original type. That means you could then create a method like this:

creating a method

and it would allow you to call it using a key of any individual property from the type you created, or an array of those properties.

You might also notice the weird type in the callback function for the data being returned from storage.

This allows us to have typed data returned from storage, as it is able to map the particular key we are requesting to the type of data that key should return.

TypeScript syntax can get a bit funky, but it is well worth the effort for all of the issues it catches before they are issues (I left this particular example untyped initially, but it was causing me so much pain that I forced myself to stop and set the types up properly first).

Learn to build modern Angular apps with my course