Ilya Chernomordik
Ilya Chernomordik

Reputation: 30255

Typescript changes visibility of types depending on the content of the file

I have a simple types.ts file:

interface Foo {
  test: string;
}

Now I can use this Foo overall in all files without importing and it compiles just fine. When I add e.g. import to the top of the file then it suddenly stops being "visible" and needs to be imported.

import { Bar } from 'Bar';

interface Foo {
  test: string;
}

I don't really understand this behaviour and cannot find documentation on this. Does typescript treat files that have only type definitions as .d.ts file or something?

Is it even a good idea to have these file in your own code (not a library) or it's better to explicitly export/import all the types?

Upvotes: 1

Views: 419

Answers (1)

Ilya Chernomordik
Ilya Chernomordik

Reputation: 30255

Have found the answer in the official documentation:

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).

Upvotes: 2

Related Questions