Cameron
Cameron

Reputation: 1047

Namespace is defined despite never being imported

Libraries or typings with an export as namespace declaration appear to be automatically polluting my code's namespace, despite me never importing them.

For example:

import * as bar from "exa";

export var t2 = (a:foo.Test) => { 
    console.log(a.doSomething());
}

export class Something {
    public test(c:foo.Test) {
        c.doSomething();
    }
}

Complete example on GitHub

What I would expect to happen is to get an error when I try to reference "foo", as I have not explicitly imported it or defined it anywhere. However, this compiles successfully.

According to the TypeScript 2.0 Handbook, namespaces exported with a export as namespace declaration should only be available if you are writing a script, which they define as "a file with no imports or exports". However in the example above, I have one import and two exports, so I don't think it counts as a script?

Therefore, why am I able to reference "foo" from my code?

This is being compiled with TypeScript 2.2

Upvotes: 0

Views: 233

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221262

You're only allowed to reference foo in type positions without an import. Attempting to use foo in a value position will raise an error.

This is because TS doesn't want to force you to write an import solely to get type information into scope, since imports have runtime side effects which you may not want.

Upvotes: 1

Related Questions