我有一个包含一堆对象的对象。这些嵌套对象中的每一个都包含键值对,其中值是URL。然后,我有一个函数将其中一个嵌套对象的名称作为输入,循环遍历该对象中的所有条目,从URL获取数据并返回具有相同键的对象,但URL字符串将替换为从URL返回的数据。
我正在寻找一种动态更改返回类型的方法,以便键与正在迭代并返回的嵌套对象的类型相匹配。
示例
// 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>发布于 2021-06-20 10:58:01
在Record<keyof typeof URLS[sport], any>中,您将根据传入的sport在URLS中查找密钥。您可以使用泛型T捕获sport的类型,然后执行URLS[T]。当然,为了做到这一点,您需要将T限制为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>https://stackoverflow.com/questions/68050063
复制相似问题