TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

File import ignored if the file containing the import statement doesn't explicitely reference a class deifined in the file

Open PezzerDev opened this issue 11 years ago • 3 comments

Class MyClass is defined in my-class.ts. The class is decorated with a custom decorator. The result of the decorator is some logic that will eventually cause MyClass to be instantiated.

Another file, other-file.ts, imports my-class.ts with:

import 'my-class';

other-file.ts has no explicit reference to MyClass, as it will automatically be instantiated and used as needed as a result of its decorator.

This works fine, until I try to import an interface, exported by my-class.ts

If I change the import within other-file.ts to:

import {ISomeInterface} from 'my-class'`;

I can now reference ISomeInterface within other-file.ts, but now the contents of my-class.ts is never actually compiled.

I suspect this is due to some optimization by the Typescript compiler. In general it would make sense that if nothing but interfaces were referenced from a class, there's no reason to generate javascript for it; however, the use of decorators makes that assumption erroneous.

PezzerDev avatar Oct 03 '15 19:10 PezzerDev

@SpenceDiNicolantonio can you provide more data, i can not get this to reproduce locally:

import {B} from "./module2";

export function decorate(c:any): void{
    // use the metadata from import B
}

@decorate
export class C {
    constructor(a: B) {
    }
}

tsc module.ts --experimentalDecorators --emitDecoratorMetadata --m commonjs --t es5

var module2_1 = require("./module2");

function decorate(c) {
    // use the metadata from import B
}
exports.decorate = decorate;
var C = (function () {
    function C(a) {
    }
    C = __decorate([
        decorate, 
        __metadata('design:paramtypes', [module2_1.B])
    ], C);
    return C;
})();
exports.C = C;

mhegazy avatar Oct 05 '15 19:10 mhegazy

And to answer your question, the compiler will elide imports that are only used in a type position. see @danquirk's answer in https://github.com/Microsoft/TypeScript/issues/4717#issuecomment-139057640 for more information. if any of these imports are used by a decorator, the import will not be elided.

mhegazy avatar Oct 05 '15 19:10 mhegazy

please reopen if https://github.com/Microsoft/TypeScript/issues/5098#issuecomment-145637425 does not answer the original question.

mhegazy avatar Nov 13 '15 06:11 mhegazy