Contents of foo.ts:
let a: Person = new Person();
Contents of bar.ts:
class Person {}
The tsconfig.json file contains the default set of values created by tsc --init
.
I'm using typescript version 2.6.2.
The code above simply compiles with no errors about Person
being not defined. If I rename Person
to Persons
in foo.ts, then it does throw an error saying cannot find name 'Persons'
. So it's as if it is automatically importing this file somehow.
Also note that I'm not exporting the Person
class in bar.ts. If I do add an export statement, then everything behaves as it should - I get an error saying cannot find name 'Person'
.
Does anyone know what's going on here? Is this a user error?
Edit:
Maybe this makes sense in the browser, but to me this behavior makes no sense in a node.js application. Is there a Typescript flag which forbids this behavior?
With TypeScript 3.8, you can import a type using the import statement, or using import type .
Key Differences Between Require and Import Require is Nonlexical and Import is Lexical. Requires to stay where they have put the file, and imports get sorted to the top of the file. Import is always run at the very beginning of the file and can't be run conditionally.
TypeScript uses the concept of modules, in the same way that JavaScript does. In order to be able to import a type from a different file, it has to be exported using a named or default export.
Your bar.ts is not a module, since it doesn't have any import nor any export. So it defines a global Person class, that doesn't need to be imported, since it's global. Export it, and TypeScript will complain about the missing import.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With