Reputation: 1182
I have an object which contains a bunch of objects. Each of those nested objects contains key value pairs where the value is a URL. I then have a function that takes the name of one of the nested objects as an input and loops over all the entries in that object, gets the data from the URL and returns an object with the same keys, but the URL string is replaced with the data returned from the URL.
I'm looking for a way to dynamically change the return type so the keys match the type of the nested object that is being iterated over and returned.
Example
// URL Object
const URLS = {
Baseball: {
Dodgers: 'url-a1',
Angels: 'url-a2',
Padres: 'url-a3',
},
Football: {
Chargers: 'url-b1',
Rams: 'url-b2',
},
}
// Function making 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>
// I'm looking for some way to do something like
Record<keyof typeof URLS[sport], any>
Upvotes: 1
Views: 1192
Reputation: 275917
In Record<keyof typeof URLS[sport], any>
you are looking for the keys inside URLS
based on passed in sport
. You can capture the type of sport
by using a generic T
and then do URLS[T]
. Of course in order to do this you need to restrict T
to be just keys in URLS
(T extends keyof typeof URLS
).
// URL Object
const URLS = {
Baseball: {
Dodgers: 'url-a1',
Angels: 'url-a2',
Padres: 'url-a3',
},
Football: {
Chargers: 'url-b1',
Rams: 'url-b2',
},
}
// Function making HTTP calls
function getUrlData<T extends keyof typeof URLS>(sport: T): Record<keyof typeof URLS[T], any> {
const values:any = {};
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>
Upvotes: 1