DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Java to TypeScript in a Day: AI Migration Playbook
  • When TypeScript Types Meet Untrusted AI: Building Type-Safe LLM Pipelines With Runtime Validation
  • Beyond the Chatbot: Engineering a Real-World GitHub Auditor in TypeScript
  • Resilient API Consumption in Unreliable Enterprise Networks (TypeScript/React)

Trending

  • Spring Security JWT Validation Best Practices
  • Build a GitHub Contribution City With Java and Quarkus
  • Choosing Voice AI Infrastructure: 7 Capabilities To Evaluate
  • Introduction to Error Prone: How to Catch Bugs at Compile Time

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. JavaScript
  4. Typescript Basics: How keyof Works

Typescript Basics: How keyof Works

Let's look at how keyof works in Typescript.

By 
Johnny Simpson
·
Mar. 21, 22 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
2.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

In Javascript and Typescript, we often run into situations where we have an object with a certain set of properties, and then another variable that 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:

JavaScript
 
let myUser = {
    name: "John Doe",
    email: "[email protected]",
    age: 15
}

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

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

    return constructedObject
}

We could imagine that ourKeys maybe 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:

TypeScript
 
type User = {
    name: string,
    email: string,
    age: 15
}
let myUser:User = {
    name: "John Doe",
    email: "[email protected]",
    age: 15
}

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:

TypeScript
 
type UserKeys = "name" | "email" | "age"

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:

TypeScript
 
type UserKeys = keyof User

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

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

type UserKeys = keyof User

let myUser:User = {
    name: "John Doe",
    email: "[email protected]",
    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
}

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.

TypeScript

Published at DZone with permission of Johnny Simpson. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Java to TypeScript in a Day: AI Migration Playbook
  • When TypeScript Types Meet Untrusted AI: Building Type-Safe LLM Pipelines With Runtime Validation
  • Beyond the Chatbot: Engineering a Real-World GitHub Auditor in TypeScript
  • Resilient API Consumption in Unreliable Enterprise Networks (TypeScript/React)

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook