Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Understand lookup types in TypeScript

    Alex Jover MoralesAlex Jover Morales

    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.

    typescriptTypeScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss