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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Beyond the Chatbot: Engineering a Real-World GitHub Auditor in TypeScript
  • Resilient API Consumption in Unreliable Enterprise Networks (TypeScript/React)
  • Supercharge AI Workflows on Azure: Remote MCP Tool Triggers + Your First TypeScript MCP Server
  • TypeScript in Cloud Applications: Why It’s a Powerful Choice

Trending

  • Optimizing High-Volume REST APIs Using Redis Caching and Spring Boot (With Load Testing Code)
  • The Hidden Cost of AI Tokens: Engineering Patterns for 10x Resource Efficiency
  • Build a GitHub Slack Bot With AWS Bedrock and MCP, Part 2
  • Testing AI-Infused Apps: A Dual-Layer Framework for AI Quality Assurance
  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 user avatar
Johnny Simpson
·
Mar. 21, 22 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
2.7K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • Beyond the Chatbot: Engineering a Real-World GitHub Auditor in TypeScript
  • Resilient API Consumption in Unreliable Enterprise Networks (TypeScript/React)
  • Supercharge AI Workflows on Azure: Remote MCP Tool Triggers + Your First TypeScript MCP Server
  • TypeScript in Cloud Applications: Why It’s a Powerful Choice

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • 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