0

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}[]

2 Answers 2

1

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']
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, cool! What if results look like this? ``` results: { item: Item; }[] | null | undefined; ```
I got it with type P = Exclude<PaginatedResult['results'], null | undefined>[number]['item']
0
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;
// }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.