【问题标题】:Typescript - Return type for nested objectTypescript - 嵌套对象的返回类型
【发布时间】:2021-06-20 10:58:00
【问题描述】:

我有一个包含一堆对象的对象。这些嵌套对象中的每一个都包含键值对,其中值是 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>

【问题讨论】:

  • function getUrlData&lt;T extends keyof typeof URLS&gt;(sport: T): Record&lt;keyof typeof URLS[T], any&gt; 会为你工作吗?
  • 是的。这就像一个魅力。谢谢!
  • 友情提示:尽量避免 TS 中的突变。 catchts.com/mutations

标签: typescript


【解决方案1】:

Record&lt;keyof typeof URLS[sport], any&gt; 中,您正在根据传入的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>

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    相关资源
    最近更新 更多