【问题标题】:TypeScript: how to extract type of array item that's nested item itselfTypeScript:如何提取嵌套项本身的数组项类型
【发布时间】:2023-01-30 13:22:04
【问题描述】:

假设我有一个这个接口的对象

interface PaginatedResult {
  results: {
   item: Item;
  }[];
  pagination: {
    pageSize: number;
    offset: number;
    total: number;
  }
}

我如何获得 Item 类型的结果 item?

如果我只想要结果类型,我会去 PaginatedResult["results"] 但那会解析为 {items: Item}[]

【问题讨论】:

    标签: typescript


    【解决方案1】:

    你可以这样做 PaginatedResult['results'][number]['item'] 像这样:

    type Item = {
      // ...
    }
    
    interface PaginatedResult {
      results: {
       item: Item;
      }[];
      pagination: {
        pageSize: number;
        offset: number;
        total: number;
      }
    }
    
    type P = PaginatedResult['results'][number]['item']
    

    【讨论】:

      猜你喜欢
      • 2021-03-26
      • 1970-01-01
      • 2019-09-08
      • 2021-12-05
      • 2019-05-06
      • 2017-06-10
      • 2013-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多