Reference .ts file for type check only

Rico Suter Source

I'd like to reference another .ts file in a .ts file. In my real project, I only need this for type safety (overriding an inherited member for correct compilation).

My sample:

Test1.ts:

export class Test1 {

}

Test2.ts:

/// <reference path="Test1.ts" />
export class Test2 {
    abc: Test1; // ERROR: Test1 could not be found
}

Is this not possible? I'd like to avoid importing as it is overhead I don't need in the outputted JavaScript file.

UPDATE: I use Test1 as amd module whose class Test1 is instanciated and injected into an instance of the class Test2 by the underlying framework. This is why i need the export keyword but don't want to directly import the module Type1 - i only need to reference the class to avoid compiler errors and have type safety etc..

typescript

Answers

answered 5 years ago jfoliveira #1

You have to add the class in a module so it can be referenced by the outside world through its module.

Example: Test1.ts

module SomeModule {
    export class Test1 {
    }
}

Test2.ts

/// <reference path="Test1.ts" />
export class Test2 {
    abc: SomeModule.Test1;
}

Optionally you can add Test2 to the same "namespace" and then reference Test1 without specify the module name:

module SomeModule {
    export class Test2 {
        abc: Test1;
    }
}

answered 5 years ago basarat #2

Without using a module loader

The export keyword at the root level of your file is only relevant if you are using some module pattern (AMD / CommonJS). If you are not the following will work:

Test1.ts:

class Test1 { // Do not use export

}

Test2.ts:

/// <reference path="Test1.ts" />
class Test2 {
    abc: Test1; // No Error
}

However if you do this you are responsible for ensuring that Test1.js is loaded before Test2.js, probably using a script tag.

NOTE: If you use a root level export without using a module loader e.g.:

export class Test2 {
}

The generated javascript:

var Test2 = (function () {
    function Test2() { }
    return Test2;
})();
exports.Test2 = Test2;

is wrong since exports is not defined anywhere.

If you are using AMD (or CommonJS):

Then you need to use an import to tell the loader to load the file:

Test1.ts:

export class Test1 {

}

Test2.ts:

// no reference to other ts required.     
import mod = module("Test1"); // Instead you need to load the module

export class Test2 {
    abc: mod.Test1; // Reference by module 
} 

Additionally

In AMD land each file is a module. So I prefer not to have a module inside the file since that another level of redirect. i.e. I will need to do importedFile.module.class instead of importedFile.class where importedFile would be what I chose to call the file on import ( I called it mod in the given example )

comments powered by Disqus