skip to Main Content

Let’s say there is a type

type Groceries = {
  details: {
    totalCost: number;
    items: Array<{
      name: string;
      price: number;
    }>
  }
}

And I want to index into the nested type of price
to type a variable let’s say

appleCost: Groceries["details"]["items"][0]["price"]

^ this throws an error that property "items" does not exist
How can I achieve this?

Doing Groceries["details"]["items"][0]["price"] is throwing an error, I believe because it is an Array type. How can I index into the individual types defined in the Array type?

Tried indexing by doing Groceries["details"]["items"][0]["price"]

2

Answers


  1. Integers are used as the indices of arrays. So to get the member values you index the array type with number.

    Or in your case:

    Groceries['items'][number]["price"]
    

    Full example:

    type Groceries = {
      totalCost: number;
      items: Array<{
        name: string;
        price: number;
      }>
    }
    
    
    type Something = {
        appleCost: Groceries['items'][number]["price"]
    }
    // `Something` is equivalent to { appleCost: number }
    

    See Playground

    Login or Signup to reply.
  2. It works totally fine for me

    let appleCost: Groceries["details"]["items"][0]["price"]
    //  ^?
    //  let appleCost: number
    
    let groc: Groceries
    let bananaCost: typeof groc['details']['items'][0]['price']
    //  ^?
    //  let bananaCost: number
    
    let price: {
        cost: Groceries["details"]["items"][0]["price"]
    } = { cost: 123 }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search