As a relatively new learner of Typescript and Javascript (with a background in Java), I have been navigating the transition from a single large Typescript file containing multiple classes to utilizing multiple classes. While I have made progress with the
import {ClassName} from './{Classname}'
syntax, along with ensuring that Classname
is preceded by export class ClassName
, I have encountered a recent setback. Initially, the transition seemed seamless, especially with my Java background where compiler errors were caught easily by Netbeans and tsc
. However, the smooth sailing came to a halt when I encountered a ReferenceError: ClassToBeImported is not defined
during runtime. It became apparent that the issue stemmed from a missing import of ClassToBeImported
, bringing into question the reliability of runtime error checks compared to IDE/transpiler errors.
While attempting to create a simplified example, it dawned on me that the problem may lie in the exporting of the referenced file. By adding or removing the export
keyword from export class NeedsToBeImported
, the error would appear or disappear accordingly.
The scenario below illustrates the error that arises:
// in file MainClass.ts
export class MainClass{
constructor(){
let x = ClassToBeImported.SOME_FIELD;
}
}
// in file ClassToBeImported.ts, same folder
export class ClassToBeImported{
static SOME_FIELD : string = "data";
}
On the other hand, the following setup does not throw an error until runtime:
// in file MainClass.ts
export class MainClass{
constructor(){
let x = ClassToBeImported.SOME_FIELD;
}
}
// in file ClassToBeImported.ts, same folder
class ClassToBeImported{
static SOME_FIELD : string = "data";
}
With the primary question surrounding the puzzling nature of this issue - specifically, why referencing a non-exported class fails to generate a transpilation error - the secondary question pertains to potential measures for enhancing code safety. Is there an option in tsconfig.json
(currently targeting es2015) that can be activated to enforce stricter checks, thereby reducing the likelihood of such runtime errors?