Assume the following class definition using TypeScript in Animal.ts:
module Animals
{
export class Animal { }
}
If I want to create a Dog class in a seperate file, say in Dog.ts using this code:
module Animals
{
export class Dog extends Animal { }
}
the name "Animal" does not exist in the current scope, is the error I get in class definition Dog.
Adding the following line to Dog.ts
/// <reference path="Animal.ts"/>
fixes the compilation error but why is this necessary, if both classes are being defined within the same module?
In other words, I want module declarations to span across files with each class or interface definition in their own file. Is this even best practice?
First of all, if you compile both files at once using
tsc Animal.ts Dog.ts
everything will be fine. When compiling Typescript files, the compiler needs to be made aware of what files actually constitue the program. This can be done using source references with ///
or by providing all files to the compiler. This is somewhat different to other languages such as java
, which compile to an intermediate representation and have a notion of a CLASSPATH
where to search for other files that are part of the program.
The /// reference is necessary because the compiler needs to know where Animal is defined somehow. It can't know what source file it's in without you telling it where to look.
I'm not sure this is a best practice per se (would need to know more about your application) but I hardly think it's an anti-pattern so I think you can feel free to do that. Modules in TypeScript are deliberately open ended to allow for this sort of pattern.
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