Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript doesn't complain about missing imports

Tags:

typescript

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?

like image 810
Shivanshu Goyal Avatar asked Jan 17 '18 17:01

Shivanshu Goyal


People also ask

Does TypeScript support import?

With TypeScript 3.8, you can import a type using the import statement, or using import type .

What is the difference between import and require in TypeScript?

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.

Do I need to export types TypeScript?

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.


1 Answers

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.

like image 162
JB Nizet Avatar answered Oct 08 '22 02:10

JB Nizet