'How to tell typescript the type of a key inside a nested loop which depends on the key before?

I have nested loop (playground link below):

    const foo: tFoo = Foo.getEmptyFooObject();

    // will be 'foo1' | 'foo2' | 'foo3'
    let firstDimensionKey: keyof typeof foo;
    for (firstDimensionKey in foo){
      const firstDimensionValues = foo[firstDimensionKey];

      // secondDimensionKey is never. Because typescript doesnt know what the firstDimensionValues is at this moment.
      // How can I make typescript know what it should be?
      let secondDimensionKey: keyof typeof firstDimensionValues;
      for (secondDimensionKey in firstDimensionValues) {
        // is there a away to avoid casting (firstDimensionKey + '-' + secondDimensionKey) as tFooFlattenedKeys?
        foo[firstDimensionKey][secondDimensionKey] = this.getValueOfFoo((firstDimensionKey + '-' + secondDimensionKey) as tFooFlattenedKeys);
      }
    }

The secondDimensionkey is never because it depends on the values firstDimensionValues holds. At least I think so.

Is is possible to let typescript know which key it is at the moment? Maybe with a conditional or mapped type? Currently we loop over every key on its own, having 10+ loops inside the function. This seems to be stupid (see playground last function: toObjectIWantToAvoid).

Edit: Type any is not allowed

Playground link



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source