Understand lookup types in TypeScript

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

Lookup types, introduced in TypeScript 2.1, allow us to dynamically create types based on the property keys of an object. We'll use the function spyOn from Jest to illustrate how lookup types can type-safe function parameters.

[00:01] The spyOn() function accepts two parameters. The first one is an object, and the second one is a property of that object to spy on. We don't care about implementation, so let's write a console.log() here. Now, let's create a person interface that will have a name, and an age as a number.

[00:28] Now, let's create the person using the person interface. Let's say name John, and age 22. At this point, we can use the spyOn() function. The problem is, it doesn't prevent us from using on an assisting property, for example, address.

[00:50] We can improve this by using lookup types. First, we need to use generics for the first parameters. Let's say o extends object. Let's use o instead. Then for the property parameter, we have to create the lookup type using the keyof operator.

[01:11] Let's write p extends keyof o. With this, we are saying, "OK, TypeScript. p is a property of the object o." Now, we see that TypeScript is complaining about the address property not existing in the object. If we rename it to name, then it works.

[01:34] Now, the remaining question is, what is the lookup type really doing? To check that, let's just store in a type what keyof person is returning. If we take a look at person types, we'll see that it returns a literal string union type with all the property names of that object.

egghead
egghead
~ 2 hours ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today