Typescript Basics: How keyof Works

Johnny Simpson - Mar 11 '22 - - Dev Community

In Javascript and Typescript, we often run into situations where we have an object with a certain set of properties, and then another variable which matches one or many keys in that object. This can cause all sorts of issues, if the keys can be edited. For example, imagine the following situation:

let myUser = {
    name: "John Doe",
    email: "xyz@fjolt.com",
    age: 15
}

function getUserDetails() {
    let ourKeys = [ "name", "red", "age" ];
    let constructedObject = {};

    ourKeys.forEach(function(item) {
        constructedObject[item] = myUser[item];
    });

    return constructedObject
}
Enter fullscreen mode Exit fullscreen mode

We could imagine that ourKeys may be coming from a database, or an API. For the purposes of explanation, I've put it in a simple array. When we run through each of these keys using our forEach loop, we output details from myUser into a new Object, called constructedObject.

The only issue is that red is not a key in myUser, but it is one in ourKeys. Ideally, the keys in ourKeys should match the keys in myUser.

Resolving mismatching keys using keyof

To resolve the issue described above, we use keyof. Let's reimagine our code in Typescript.

Custom Types

We'll be using custom types today. If you're unfamiliar with them, read our guide on custom types in Typescript here.

First, let's give our myUser object a custom type:

type User = {
    name: string,
    email: string,
    age: 15
}
let myUser:User = {
    name: "John Doe",
    email: "xyz@fjolt.com",
    age: 15
}
Enter fullscreen mode Exit fullscreen mode

Now, let's define our type for ourKeys. Essentially, we want ourKeys to be either name, email or age. One way we can define this, is like so:

type UserKeys = "name" | "email" | "age"
Enter fullscreen mode Exit fullscreen mode

This works, in theory, but it's not necessarily full proof - what if the User type changes down the line, and we forget to update UserKeys? We'll run into some issues. Instead, we can write the above line like this, which means the exact same thing:

type UserKeys = keyof User
Enter fullscreen mode Exit fullscreen mode

This means UserKeys is a type which translates to "name" | "email" | "age" - but will always stay in sync with User. Now we've constructed our types, let's update our code:

type User = {
    name: string,
    email: string,
    age: number
}

type UserKeys = keyof User

let myUser:User = {
    name: "John Doe",
    email: "xyz@fjolt.com",
    age: 15
}

function getUserDetails() {
    let ourKeys:UserKeys[] = [ "name", "email", "age" ];
    let constructedObject:Partial = {};

    ourKeys.forEach(function(item:K) {
        if(typeof myUser[item] !== "undefined") {
            constructedObject[item] = myUser[item];
        }
    });

    return constructedObject
}
Enter fullscreen mode Exit fullscreen mode

Now if ourKeys contains "red", we'll get an error - so it should always register the correct keys. As you can see, keyof makes writing our Typescript slightly easier, and reduces the maintenance burden. You can read more about typescript here.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .