Creating an object key using a passed literal argument in TypeScript

Can the following scenario be achieved? Given an argument, how can we identify the object key and access it?

Any potential solutions?

async function checkKey(arg:'key1'|'key2'){
  // fetchResult returns an object with either {key1:'result1'} or {key2:'result2'}
  const obj:{[arg]:string} = await fetchResult('url')
  console.log(obj[arg])
}

await checkKey(key1) //Expecting to see 'result1'

await checkKey(key2) //Expecting to see 'result2'

Answer â„–1

Your inquiry revolves around dynamically creating an interface from a string union type. To handle scenarios where the fetch function result contains both types of keys, you can iterate over the argument type instead of setting a specific value.

const data: {[key in typeof argument]: string} = await fetchResults('api-url')

It seems unnecessary to further specify the type since the statement data[argument] will always be of type string based on the provided information.

If there is a need to narrow down the type for specific outcomes, why not directly specify them? You have knowledge of the return structure from the fetch call, so it's feasible to define the exact values.

async function retrieveData<S extends 'type1' | 'type2'>(argument: S){
  // fetchResults delivers either {type1:'outcome1'} or {type2:'outcome2'}
  const data: {type1: "outcome1", type2: "outcome2"} = await fetchResults('api-url')
  return data[argument];
}

(async () => {
  const result1 = await retrieveData("type1"); // result1 is of type "outcome1"
  const result2 = await retrieveData("type2"); // result2 is of type "outcome2"
})()

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

Conflicting behavior between jQuery focus and blur functions and retrieving the 'variable' parameter via the $_GET method

There is a simple focus/blur functionality here. The default value shown in the 'Name of Venue' input field changes when the user clicks on it (focus) and then clicks away(blur). If there is no text entered, the default value reappears. Input fi ...

The dependency path in the package.json file contains all the necessary files

I recently developed a JavaScript package and here is the configuration in my package.json: { "name": "packageName", "version": "1.0.0", "description": "Description of the package", " ...

When executing npm release alongside webpack, an error is triggered

Currently, I am following a tutorial provided by Microsoft. You can access it through this link: https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr-typescript-webpack?view=aspnetcore-3.1&tabs=visual-studio However, when attempting to run ...

Troubleshoot redirect issues in JavaScript or PHP

I am facing a simple issue that is proving to be time-consuming to solve. The challenge that I am encountering involves an HTML form with 2 buttons. Here is the relevant code snippet: $html1 = "<div class='pai-forms'> <form ...

Does using breakpoints in strict mode affect the outcome?

Here is the code snippet: 'use strict'; var foo=function(){ alert(this); } var bar = { baz:foo, }; var x = bar.baz; x();//1 After executing the code directly, everything works fine and it alerts undefined. However, when I insert a break ...

Are there any methods to incorporate Facebook and Google login into an Ionic progressive web app (PWA)?

After successfully developing an app in Ionic 3 for Android and iOS, I encountered a problem when adding the browser platform. The Facebook and Google login features were not functioning as expected. Despite the assurance from Ionic documentation that the ...

Guide to reference points, current one is constantly nonexistent

As I work on hosting multiple dynamic pages, each with its own function to call at a specific time, I encounter an issue where the current ref is always null. This poses a challenge when trying to access the reference for each page. export default class Qu ...

What should be the proper service parameter type in the constructor and where should it be sourced from?

Currently, I am faced with a situation where I have two Angular 1 services in separate files and need to use the first service within the second one. How can I properly type the first service in the constructor to satisfy TypeScript requirements and ensure ...

Testing MatDialog functions in Angular: Learning how to open and close dialogues

I am currently facing an issue with testing the MatDialog open and close functions. No matter what I try, I cannot seem to successfully test either the open or close functions. I am wondering how I can mock these functions in order to properly test them. W ...

jQuery fails to locate class following AJAX reply

In my application, there is a cart feature where users can remove items from their cart, triggering a refresh of the contents using AJAX. However, I noticed that after removing an item from the cart, the response switches from asynchronous to synchronous m ...

What is the process for updating button text upon clicking in Angular?

To toggle the text based on whether this.isDisabled is set to false or true, you can implement a function that changes it when the button is clicked. I attempted to use this.btn.value, but encountered an error. import { Component } from '@angular/core ...

I am looking to switch from a hamburger menu to a cross icon when clicked

Hey there, I'm currently working on a Shopify website and trying to make the hamburger menu change to a cross when clicked. I've been experimenting with different methods, but unfortunately haven't had any success so far. I have two images â ...

How can I designate the file name when using Ajax to export in Excel formatting?

Can you help me with the code to set a specific filename for downloading an Excel file? if(comp_id != "Select Company") { $.ajax({ url: 'includes/export.php', data: { action: 'compreport', 'comp':comp_i ...

Issues with Angular preventing app from launching successfully

So I've been working on a Cordova app with AngularJS and everything seems to be running smoothly in Chrome and other browsers. However, when I try to install the apk on Android, AngularJS doesn't seem to execute the index.html upon launch. What& ...

Which is more efficient for optimizing code: Typescript compiler or ES2015?

When it comes to compiler optimization in other programming languages, a similar scenario would involve pulling out certain objects from the loop to avoid creating them each time: const arr = [1, 2, 3, 4, 5] arr.map(num => { const one_time = 5; / ...

Using Python Selenium to interact with elements on a web browser and make edits

Is there a way to modify an element in a web browser using Python 2.7 Selenium? Consider this element: <span id="some-random-number">100</span> While you can retrieve the text with: driver.find_element_by_id("some-random-number").text how c ...

Adjusting canvas context position after resizing

I've been experimenting with using a canvas as a texture in three.js. Since three.js requires textures to have dimensions that are powers of two, I initially set the canvas width and height to [512, 512]. However, I want the final canvas to have non-p ...

The autoIncrement feature is causing a syntax error at or near "SERIAL"

Encountering a build error : Unable to start server due to the following SequelizeDatabaseError: syntax error at or near "SERIAL" This issue arises only when using the autoIncrement=true parameter for the primary key. 'use strict'; export ...

Retrieving an HTML element that has been added through DOM manipulation

After successfully creating a Jquery function that inserts a 'save button' into the page when a specific button is clicked, I encountered an issue with another function meant to be activated when the save button is clicked. The first function see ...

Using JavaScript to create a search bar: Can "no results found" only show after the user has completed typing their search query?

How can I ensure that the "no match" message only appears after the user has finished typing in their search query, rather than seeing it while they are still typing "De" and the list displays "Demi"? usernameInput.addEventListener("keyup",function(){ ...