0

I have 2 typescript files -

a.ts:

let some : string = "some";

b.ts:

console.log(some);

If I compile both files by adding them to include option in tsconfig (or by giving both on the command line), there is no error about some being undefined in b.ts. How can I compile both files separately? It doesn't even make sense for them to share namespace in the first place.

1 Answer 1

1

There is no namespace in JavaScript. If you load the two compiled files in a browser (in the right order), the console.log will work. TypeScript reproduces this feature.

The JavaScript (and TypeScript) way is to use ES6 modules, for example with Webpack.

Your example with modules:

// a.ts
export let some = "some";

// b.ts
console.log(some); // Error here

// c.ts
import { some } from "./a"
console.log(some); // OK
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. One thing I want to do is be able to define same namespace in multiple files but still be able to refer variables (in the same namespace) in other files without using the namespace variable. Is it possible?
With TypeScript namespaces? No, it's not possible. Namespaces are compiled to multiple IIFE, variables are accessible only in the local IIFE.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.