0

I have Project 1 and Project 2. After coping some file, lets say it be validators/index.ts from Project 1 to Project 2, I experienced a strange problem: even if files referenced by copied file via require are not exists, TypeScript compilation success and no errors are shown.

In short, the code I talking about is something like this:

type BuilderFunc = (factory:IValidatorsFactory) => Validator;
function  registerMetaTypeViaBuilderFunction(builderFunc:BuilderFunc) {
  let validator = executeBuilderFunc(factory, builderFunc);
  //errors handling and duplicate checks cropped away as irrelevant for this issue
  validatorsMap.set(validator.id, validator);
}
registerMetaTypeViaBuilderFunction(require('./existing-validator'));
registerMetaTypeViaBuilderFunction(require('./other-validator'));
registerMetaTypeViaBuilderFunction(require('./missing-validator'));
registerMetaTypeViaBuilderFunction(require('./existing-validator3'));
registerMetaTypeViaBuilderFunction(require('./forgot-to-copy-file'));
registerMetaTypeViaBuilderFunction(require('./last-validator'));

and TypeScript compilation was successful even the missing-validator.js and forgot-to-copy-file are missing.

Whole point of migration from raw JS to TS was hope to catch this sort of errors automatically by IDE/compiler.

BTW, IDE is WebStorm.

LazyOne
  • 158,824
  • 45
  • 388
  • 391
Kote Isaev
  • 273
  • 4
  • 13

1 Answers1

1

require is a function, so it's not evaluated at compile time, rather it is invoked at runtime.

It's a runtime "loader".

So there's no way for the compiler to check that the required module / file exists.

For a deeper discussion, see What is this Javascript "require"?

If you want compile-time checking, then you probably want "import" instead of "require".

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
  • I accepted your answer, and want add some note: May be I was been confused by TS when sometimes it can be smart enough to give errors reports like "there is no function A in type require('../foobar')" so I expected it would understand that there is NO such file as `./missing-validator') but it seems it just fallback to `any` type, probably, for such case. Meanwhile, for requires like `require("package-name")` IDE is able to report at least a warning. But not in such case somehow. – Kote Isaev Jul 16 '21 at 11:56