Skip to content

Changes in namespaced variables are not reflected in namespaced functions #6347

@Codeneos

Description

@Codeneos

Reproduction link or steps

Updating an exported a variable from a namespace outside of the namespace causes the change only to be reflected outside of the namespace. Functions that are defined in the namespace that use the variable see a different version.

Below code defines namespace Foo with fuction bar and exports variable baz

export namespace Foo {
  export let baz = 1;
  export function bar() {
    return ++baz;
  }
}
Foo.baz = 10;
console.log(Foo.bar()); // Should print 11 - but prints 2
console.log(Foo.bar()); // Should prints 2
console.log(Foo.baz); // Still prints 1;

Comparing tsdown's compilation of namespace foo:

let Foo;
(function(_Foo) {
	let baz = _Foo.baz = 1;
	function bar() {
		return ++baz;
	}
	_Foo.bar = bar;
})(Foo || (Foo = {}));

Typescript's tsc instead does something more like:

let Foo;
(function(_Foo) {
	_Foo.baz = 1;
	function bar() {
		return ++_Foo.baz;
	}
	_Foo.bar = bar;
})(Foo || (Foo = {}));

See: https://stackblitz.com/edit/github-mdhsyejm?file=src%2Fns.ts

What is expected?

When you update a variable defined in a namespace that variable is also visisble with the same value by functions inside of the namespace.

What is actually happening?

Functions inside of the namespace see a different version of exported variables then external functions. Meaning you cannot read the current state of the variable defined in the namespace nor can it be changed.

Any additional comments?

No response

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingtsdown

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions