Creating object types in typescript from object keys: a step-by-step guide

In my JavaScript object, I have two keys named foo and bar.

const x = { foo: '', bar: '' }

I also have a function called abc that takes a value (which can only be either foo or bar).

function abc(value: string) {

 const selected = x[value];
}

Currently, the value is of type string. However, I want it to be foo or bar (since they are present in the x object). I attempted to change it using

  function abc(value: typeof x)

But TypeScript does not accept that.

How can I modify my code to achieve the desired functionality?

Answer №1

If you use the keyof operator with the typeof keyword followed by X, it will extract each key of the type of the variable X which includes:

{
  foo: string;
  bar: string;
}

For this function to work properly, it should be defined as follows:

function abc(value: keyof typeof x)

The type of the value parameter will be either "foo" or "bar"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating assets from typescript plugins in Angular 6: A comprehensive guide

Situation I am currently in the process of migrating from Angular 4 and Angular Seed to Angular 6 and Angular CLI. Challenge One issue I am facing is with dynamic loading of plugins within a component using SystemJS. SystemJS.import("client/plugins/" + ...

Show a nested JSON object when the specific key is not recognized

I received the following data from my API: { "id": 82, "shortname": "testing2", "fullname": "test2", "address": "addrtest2", "telephone" ...

Updating the DOM with an EventListener in Angular 5 is not functioning properly

Situation : Utilizing an Angular PWA for communication with an iOS native app via WKWebview. Implementing messageHandlers to facilitate data sharing between TypeScript and Swift logic code. Issue : Employing addEventListener to monitor a specific event on ...

Error: "the cart variable in the ctx object has not been defined"

A project I'm currently working on involves a pizza ordering app, and my current focus is on implementing the Cart feature. Each user has their own cart, which includes specific details outlined in cart.ts import { CartItem } from './cartitem&a ...

Tips for integrating Excel files with NestJS

I'm in the process of developing a REST API that will utilize a third-party API to retrieve specific status information. The URLs needed for this API are stored in an Excel file, which is a requirement for this use case. My goal is to extract the URLs ...

Material UI is not capable of utilizing Props

I'm having trouble using the Checkbox component from Material UI. Even though I can't seem to use the normal props like defaultChecked or size="small", as it gives me the error TS2769: No overload matches this call. TS2769: No overload ...

There are no properties associated with this particular data type

As someone who is new to TypeScript, I am encountering two issues with data types. This snippet shows my code: const say: object = { name: "say", aliases: [""], description: "", usage: "", run: (client: ob ...

Struggling with the Transition from Google Sign-In

Having difficulty transitioning from Google Sign-In. "{error: 'idpiframe_initialization_failed', details: 'You have created a new client application that use…i/web/guides/gis-migration) for more information.'}" How do I u ...

What is the best way to modify the quantity property of a cart item object within the framework of this Angular 13 online shopping application?

I am currently developing an e-commerce app with a front-end built using Angular 13. The following code snippet is designed to calculate the total price of items in the shopping cart: import { Component, OnInit } from '@angular/core'; @Componen ...

What is the method to insert a new <input> element after the last input field has been filled in

I recently started working on a form using StackBlitz, but I've hit a roadblock and need some guidance on how to proceed. My goal is to achieve a similar effect like the one shown in this gif: https://i.stack.imgur.com/76nsY.gif and I'd like to ...

What is the best way to link three different types of http requests in succession and adaptively?

Is it possible to chain together 3 types of http requests correctly, where each request depends on data from the previous one and the number of required requests can vary? In my database, there is a team table with a corresponding businessId, a supervisor ...

Using the pipe operator in RXJS to transform an Event into a KeyboardEvent

I'm encountering an error when trying to add a keydown event and convert the parameter type from Event to KeyboardEvent as shown below. fromEvent(document, "keydown") .pipe<KeyboardEvent, KeyboardEvent>( filter((event) => even ...

An issue arises when trying to update state using useState in TypeScript

In our system, we have a state that contains an array of objects: interface Product { id: number; status: boolean; color: string; price: number; } const productList: Product[] = [ { id: 1, status: true, color: 'yellow', ...

Guide on creating path aliases for Storybook webpack configuration

Currently, I am integrating Storybook with nextjs and webpack. Below is my configuration in .storybook/main.ts: import type { StorybookConfig } from '@storybook/nextjs'; const config: StorybookConfig = { ... framework: { name: '@sto ...

Unable to make changes to the document

Having trouble updating a document by ID using mongoose and typescript. I'm testing the api and passing the id as a parameter. I've experimented with different methods of updating by ID, but for some reason, it's not working. Can update by ...

The Mat table is not updating on its own

I am facing an issue in my Angular application where a component fetches a hardcoded list from a service and subscribes to an observable to update the list dynamically. The problem arises when I delete an element from the list, as it does not automaticall ...

Tips for implementing generics in an abstract class that extends a React Component

I am in the process of developing a unique abstract class that extends a React Component. My goal is to establish default Props while allowing the components that extend the abstract class to supply their own props. interface Props { ...

Unable to translate text on the loading page

Encountering a peculiar issue with the translate service. Here's how I set it up: export class AppComponent implements OnInit { constructor( private translateService: TranslateService, angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics ...

Are there more efficient methods for utilizing local scope when defining a variable?

Having experience in the ML world, I'm used to creating variables with limited scope like this: let myVar = let result1 = doSomething() let result2 = doSomethingElse() result1 + result2 In TypeScript, it seems you can achieve similar sco ...

NextJS applications can encounter issues with Jest's inability to parse SVG images

Upon running yarn test, an unexpected token error is encountered: Jest encountered an unexpected token This typically indicates that Jest is unable to parse the file being imported, suggesting it's not standard JavaScript. By default, Jest will use ...