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?
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.