How to type a subproperty of a nested object?

Viewed 126

I know this sounds like a generic question, but I wasn't quite able to find an answer online.

Suppose I have the following object,

const myObject = {
    property: {
        subProperty: null
    },
}

The following works just fine:

const getValue = (): string => 'property'

const value = myObject[getValue() as keyof typeof myObject]

However when I try to type the subProperty value, I get an error. Here's how I try typing it:

const getValue = (): string => 'property'
const getSubValue = (): string => 'subProperty'

const value = myObject[getValue() as keyof typeof myObject]

const subValue = myObject[getValue() as keyof typeof myObject][getSubValue() as keyof typeof myObject[getValue() as keyof typeof myObject]]

I'm aware that I can change the two methods to the following:

const getValue = (): 'property' => 'property'
const getSubValue = (): 'subProperty' => 'subProperty'

This will work without the keyof typeof indicator, but obviously I need to keep the return value of the two functions to be string.

1 Answers

It appears that the TypeScript parser isn't able to handle the complexity of the expression. So if you use an intermediate variable, it will work:

const value = myObject[getValue() as keyof typeof myObject]
const subValue = value[getSubValue() as keyof typeof value]
Related