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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Subtitles: The Good, the Bad, and the Resource-Heavy
  • Integrating Jenkins With Playwright TypeScript: A Complete Guide
  • Efficiently Migrating From Jest to Vitest in a Next.js Project
  • Implement a Geographic Distance Calculator Using TypeScript

Trending

  • Go 1.24+ Native FIPS Support for Easier Compliance
  • Creating a Web Project: Caching for Performance Optimization
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 2
  • Modern Test Automation With AI (LLM) and Playwright MCP
  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
DZone Core CORE ·
Mar. 21, 22 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
2.6K 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: "xyz@fjolt.com",
    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: "xyz@fjolt.com",
    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: "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
}

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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Subtitles: The Good, the Bad, and the Resource-Heavy
  • Integrating Jenkins With Playwright TypeScript: A Complete Guide
  • Efficiently Migrating From Jest to Vitest in a Next.js Project
  • Implement a Geographic Distance Calculator Using TypeScript

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!