Typescript - Specifying the return type for a deeply nested object

I have a container that holds multiple sub-containers, each containing key-value pairs where the value is a URL. I also have a function that takes the name of one of the sub-containers as input, loops through its entries, fetches data from the URLs, and returns an object with the same keys but updated values.

I am seeking a method to dynamically adjust the return type so it aligns with the nested object being processed and returned.

For example:

// URL Object
const URLS = {
  Baseball: {
    Dodgers: 'url-a1',
    Angels: 'url-a2',
    Padres: 'url-a3',
  },
  Football: {
    Chargers: 'url-b1',
    Rams: 'url-b2',
  },
}

// Function for HTTP calls
function getUrlData(sport: string): Record<???, any> {
  const values = {}
  Object.entries(URLS[sport]).forEach(([team, url]) => {
    values[team] = httpGet(url)
  })
  return values
}

getUrlData('Baseball') // Return type: Record<keyof typeof URLS.Baseball, any>
getUrlData('Football') // Return type: Record<keyof typeof URLS.Football, any>

// Can we achieve something like
Record<keyof typeof URLS[sport], any>

Answer №1

When you use

Record<keyof typeof URLS[sport], any>
, you are specifically targeting the keys within the URLS object based on the provided sport. To achieve this, you can define a generic type T to represent the type of sport and then access the corresponding values using URLS[T]. However, it is essential to restrict the generic type T to only accept keys that exist in the URLS object (T extends keyof typeof URLS).

Detailed Demonstration

// Sample URL Object
const URLS = {
  Basketball: {
    Lakers: 'url-x1',
    Clippers: 'url-x2',
  },
  Soccer: {
    Galaxy: 'url-y1',
    LAFC: 'url-y2',
  },
}

// Function for fetching data from URLs
function fetchUrlData<T extends keyof typeof URLS>(sport: T): Record<keyof typeof URLS[T], any> {
  const result:any = {};
  Object.entries(URLS[sport]).forEach(([team, url]) => {
    result[team] = httpFetch(url)
  })
  return result;
}

fetchUrlData('Basketball') // Output type: Record<keyof typeof URLS.Basketball, any>
fetchUrlData('Soccer') // Output type: Record<keyof typeof URLS.Soccer, any>

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

How can the service receive the return value from a subscribed subject?

I have a question about whether it is possible to retrieve the value from a call to Subject.next(). Can you suggest any other approaches on how to receive a response in the given scenario? My current situation involves a notify service that is used throug ...

Tips for adjusting the radio button value similarly to a checkbox in Angular 2 using *ngFor

my checkbox and radio button implementation: <input id="{{k.group_name}}_{{i}}" name="{{k.group_name}}" type="checkbox" class="hide" name="{{k.group_name}}" [value]="m.details" (change)="change($event, m , k.item_ingredient_group_key,false,k.maximum)"& ...

Can someone show me how to implement RequestPromise in TypeScript?

I recently integrated the request-promise library into my TypeScript project, but I am facing some challenges in utilizing it effectively. When attempting to use it in the following manner: import {RequestPromise} from 'request-promise'; Reque ...

What is the best way to effectively use combinedLatestWith?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/country-card/country-card.component.html I am currently working on implementing a search bar in Angular that filters the "countries$" Observable based on user input. My approach involves creatin ...

Data that changes dynamically on a chart

When making a rest call to fetch data, I aim to populate the pieChartData with the obtained information. However, I am facing difficulties in achieving this task. Can someone guide me on how to accomplish this? import { Component, OnInit} from '@angu ...

Is there a way to modify the scroll ion-content's color scheme?

Is there a way to change the scroll color in Ionic to green, specifically for ion-content? Any suggestions on how I can achieve this? Below is my HTML code: <ion-header> <ion-toolbar> <ion-buttons slot="start"> ...

The issue with converting a string into an object in Typescript

I am having trouble converting the JSON response from the websocket server to a TypeScript object. I've been trying to debug it but can't seem to find where the error lies. Can anyone assist me in resolving this issue? Below is the code snippet ...

Comparison of valueChanges between ReactiveForms in the dom and component级主动形

Is there a method to determine if the change in valueChanges for a FormControl was initiated by the dom or the component itself? I have a scenario where I need to execute stuff() when the user modifies the value, but I want to avoid executing it if the v ...

What are the best practices for utilizing an array of routes?

I'm new to working with react but I noticed something strange. My routes are currently set up like this: <Main> <Route exact path="/home" component={Home} /> <Route exact path="/home1" com ...

The quantity of documents queried does not align with the number of data counts retrieved from Firestore

Facing an issue with calculating the Firestore read count as it keeps increasing rapidly even with only around 15 user documents. The count surges by 100 with each page reload and sometimes increases on its own without any action from me. Could this be due ...

Ways to utilize a field from an interface as a type of index

interface Mapping { "alpha": (a: string) => void "beta": (b: number) => void } interface In<T extends keyof Mapping> { readonly type: T, method: Mapping[T] } const inHandlers: In<"alpha"> = { type ...

A guide on implementing TypeScript with React Native's platform-specific extensions

The issue at hand: In my react native project, I am using a custom hook that has platform-specific code. I need to import this hook based on the platform in use. When I import it as import useWifi from 'hooks/use-wifi.android';, everything works ...

When using react-admin with TypeScript, it is not possible to treat a namespace as a type

Encountering issues while adding files from the react-admin example demo, facing some errors: 'Cannot use namespace 'FilterProps' as a type.' Snippet of code: https://github.com/marmelab/react-admin/blob/master/examples/demo/src/orde ...

When trying to run ionic serve, I encountered the following error: "[ERROR] ng has unexpectedly closed with an exit code of 127."

My attempt to launch an ionic app on my Mac has hit a roadblock. While running npm install for the dependencies, everything goes smoothly without any issues. However, when I try to run 'ionic serve' or 'ionic s', an error crops up: [ng] ...

`How to prevent Query parameters from being lost upon reloading in Nextjs Router while maintaining a clean URL structure?`

My challenge lies in sending data via router.push to a page with dynamic room id (src/pages/editor/[roomid].tsx) in Next.js. I want the URL to stay clean so users can easily edit their username in the URL if needed. When initially loaded, router.query suc ...

Encountering a Problem with HTTP Requests in Angular 2

Seeking assistance with a technical issue. My objective: Make a REST API call to retrieve JSON data and resolve an Angular 2 promise. ServerAPI built with Node.js/ExpressJS/Lodash Sample of server.js file: var express = require('express'); va ...

The Nestjs ClientMqtt now has the capability to publish both pattern and data to the broker, as opposed to just sending

I am currently utilizing Nestjs for sending data to a Mqtt Broker. However, I am facing an issue where it sends both the pattern and data instead of just the data in this format: { "pattern": "test/test", "data": " ...

Tips for modifying the type definition of a third-party library in a Vue project built with Create-Vue

After updating the Cesium library in my Vue project, I encountered some errors. This is the code snippet: camera.setView({ destination, orientation: { heading, pitch } }) The error message reads: Type '{ heading: number; pitch: number; }' i ...

Creating a single definition that encompasses the characteristics of both primitive and generic types without the need for combining them

Here is a scenario where I need to consolidate and refactor two types: ... .then((result1: any) => { let promises = { one: $q.when(val1), two: $q.when(val2) }; return $q.all(promises); }) .then((resolvedPromises: any) => { ...

Explain the form of an object using typescript without considering the categories

I'm looking to define the shape of an object in TypeScript, but I want to disregard the specific types of its fields. interface TestInterface { TestOne?: string; TestTwo?: number; TestThree?: boolean; } My approach was to define it like this: ...