#Namespaces and variables type checking

1 messages · Page 1 of 1 (latest)

sick warren
#

Hello, I am using a code-generation library and had trouble wrapping my mind around some issue. Take a look at the following piece of code:

export namespace components {
  export const component2 = {
    component1Flag: components['component1'].flag
  }
  export const component1 = {
    flag: true
  }
}

On a strict type level, this works. Typescript sees no type issue in the previous code. However, at runtime this piece of code fails with the error components['component1'] is undefined on line 3.

Why is this code authorized at the type level while it doesn't run?

Thank you

royal kiln
#

@sick warren because a module simply declares different objects

#

and the order those objects are declared in is kinda lost in the process

#

but the order matters at runtime ofc

royal kiln
#

the order the objects are created doesn't for the consumers of the module, only within the module itself

#

it's the same reason recursive import loops also exist

#

declaring objects is one thing

#

instantiating them and giving them a value in the right order is another

#

tldr. refering to the current module and accessing objects from it is a bad idea