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
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:
Full example:
See Playground
It works totally fine for me