Objects 16 exercises

Using the PropertyKey Type in TypeScript

The obvious answer is to change the key's type to string | number | symbol:

const hasKey = (obj: object, key: string | number | symbol) => {
return obj.hasOwnProperty(key);

This change fixes all of the errors, but there's a more interesting answer.

Inside of the `hasK

Loading solution


00:00 So the obvious solution here is to say string or number or symbol. Okay, beautiful. Everything just works. So we now accept any one of these three things. We hover over HasKey, we can see we have string or number or symbol. But what if I told you there was a more concise way, a more TypeScript native way of doing this?

00:19 Well, we can use, if we hover over this, we can see that object.hasOwnProperty, if we command click on it, it takes in a type of property key. And property key is a globally available type, available in any version after ES5. So we can use property key inside here. So key now takes property key.

00:39 Beautiful. Property key is useful in all sorts of little situations like this where you want to model all the possible keys that an object can take. So it's useful for index signatures and really useful for this particular case too.