Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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?

like image 765
Dave Houlker Avatar asked Aug 31 '25 10:08

Dave Houlker


2 Answers

This works:

type SubItems = Example["items"][string]["value"];
like image 122
cyco130 Avatar answered Sep 05 '25 09:09

cyco130


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
like image 40
Majid M. Avatar answered Sep 05 '25 07:09

Majid M.