How to access the type of a property in a nested type below an indexer?

Viewed 106

Given:

interface Example {
    items: {
        [k: string]: {
            name: string;
            value: {
                subName: {
                    subValue: string;
                };
            };
        };
    };
};

It's possible to create a type for items with a lookup type:

type Items = Example['items'];

But what if I want to get the type below the indexer?

type SubItems = Example['items']['']['value'];

The above won't work. Is there a way to access the type of the value object?

3 Answers

This works:

type SubItems = Example["items"][string]["value"];

You can access it hierarchically. Please look at this:

interface Example {
    items: {
        [k: string]: {
            name: string;
            value: {
                subName: {
                    subValue: string;
                };
            };
        };
    };
}

var example = {
  items:{
    'item':{
      name:'1',
      value:{
        subName:{
          subValue:'2'
        }
      }
    }
    } 
} as Example

console.log(example['items']['item']['value']['subName']['subValue']); //2

Do it the other way around. Specify your types explicitly:

interface ItemValue {
    subName: { subValue: string }
}

interface Item {
    name: string;
    value: ItemValue;
}

interface Example {
    items: {
        [k: string]: Item
    }
}
Related