3

Burning through a typescript course I came across these code pieces that fail to compile and give error TS2304. Any help is appreciated.

file ZooAnimals.ts:

namespace Zoo {
    interface Animal {
        skinType: string;
        isMammal(): boolean;
    }
}

File ZooBirds.ts:

/// <reference path="ZooAnimals.ts" />
namespace Zoo {
    export class Bird implements Animal {
        skinType = "feather";
        isMammal() {
            return false;
        }
    }
}

The command to compile the files:

tsc --outFile Zoo.js ZooAnimals.ts ZooBirds.ts

Throws error:

ZooBirds.ts:3:34 - error TS2304: Cannot find name 'Animal'.

3     export class Bird implements Animal {

1 Answer 1

2

To use the interface across files (or more precisely across multiple namespace declarations) it must be exported (even if it is part of the same namespace). This will work:

namespace Zoo {
    export interface Animal {
        skinType: string;
        isMammal(): boolean;
    }
}
namespace Zoo {
    export class Bird implements Animal {
        skinType = "feather";
        isMammal() {
            return false;
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

That certainly works - thanks. The edX course (from Microsoft) suggests to use '/// <reference path='...' /> ' tag to resolve the inclusion of the Animal definition and not export the interface. But somehow the reference path does not seem to be working. Wondering if I am doing something wrong or the version of typescript that can only work as suggested by you.
@rks The <reference...> might still be needed for the definitions to be discovered. But the export is most definitely required..
Actually it works without needing the <reference .../> tag if the interface is exported. Here is the code from the course: ZooAnimals.ts namespace Zoo { interface Animal { //note that we do not need the *export* here since this interface will only be accessible only by entities from within the Zoo namespace skinType: string; isMammal(): boolean; } }
@rks it should work without the ///<ref as well if all the files are included in the compilation .. it was probably an oversight in the course..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.