Home > Blockchain >  TypeScript: how to extract type of array item that's nested item itself
TypeScript: how to extract type of array item that's nested item itself

Time:01-30

Let's say I have an object of this interface

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

How do I get that Item type of results item?

If I'd wanted just type of results I'd go PaginatedResult["results"] but that resolves to {items: Item}[]

CodePudding user response:

You can do PaginatedResult['results'][number]['item'] like so:

type Item = {
  // ...
}

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

type P = PaginatedResult['results'][number]['item']

CodePudding user response:

type Item = {
  ItemId: number,
  ItemName: string
}

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

const o: PaginatedResult = {
  results: [
    { item: {ItemId: 1, ItemName: "Item1"}},
    { item: {ItemId: 2, ItemName: "Item2"}}
  ],
  pagination: {
    pageSize: 2,
    offset: 2,
    total: 69
  }
}

type NewItem = typeof o.results[0]["item"]
// hovering over NewItem shows
// type NewItem = {
//    ItemId: number;
//    ItemName: string;
// }
  • Related