Rotareti
Rotareti

Reputation: 53813

Recursive type not working for nested objects with unknown fields

I'm trying to create a recursive type (Foo) for a nested object with unknown fields:

interface Foo {
  [key: string]: number | Foo;
}

const foo: Foo = {
  a: 1,
  b: {
    c: 2,
    d: {
      e: 3,
      f: 3
      // etc...
    }
  }
};

const bar = foo.b.d;

With the code above I get an error on the last line:

Property 'd' does not exist on type 'number | Foo'.
  Property 'd' does not exist on type 'number'.ts(2339)

Does anyone know why this doesn't work and how to solve it?

Upvotes: 0

Views: 1266

Answers (1)

SpencerPark
SpencerPark

Reputation: 3506

The type of foo.b is number | Foo. Typescript here is preventing you from trying to access field d (or any field) on a number.

You need to assert that foo.b is actually a Foo and not a number or change the type of your object.

If you know for certain that it is a Foo then const bar = (foo.b as Foo).d should do the trick. Otherwise moving it into an if statement while narrowing the type with a typeof check to make sure it != number.

Upvotes: 3

Related Questions