Search code examples
requirejstypescriptamd

Where does the "use strict" go when using TypeScript and AMD Modules


I am using TypeScript version 1.0.1.0

When using TypeScript and AMD modules together, where exactly should I write the "use strict" statement? Should it go above or below the imports?

I can write it above the imports, so that this TypeScript code:

"use strict";
import Backbone = require('backbone');
class MyClass extends Backbone.View<Backbone.Model> { }
export = MyClass;

results in this JavaScript with the statement at the top of the file:

"use strict";
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define(["require", "exports", 'backbone'], function(require, exports, Backbone) {
    var MyClass = (function (_super) {
        __extends(MyClass, _super);
        function MyClass() { _super.apply(this, arguments); }
        return MyClass;
    })(Backbone.View);
    return MyClass;
});

Or I can put the "use strict" statement below my imports. So that this TypeScript:

import Backbone = require('backbone');
"use strict";
class MyClass extends Backbone.View<Backbone.Model> { }
export = MyClass;

Results in this Javascript with the statement at the top of the RequireJS function declaration:

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define(["require", "exports", 'backbone'], function(require, exports, Backbone) {
    "use strict";
    var MyClass = (function (_super) {
        __extends(MyClass, _super);
        function MyClass() { _super.apply(this, arguments); }
        return MyClass;
    })(Backbone.View);
    return MyClass;
});

Which one is correct? TSLint does not report a violation even when the statement is missing entirely. Is that perhaps a bug in TSLint?


Solution

  • The first variation results in whole-script strictness:

    "use strict";
    import Backbone = require('backbone');
    class MyClass extends Backbone.View<Backbone.Model> { }
    export = MyClass;
    

    The second limits the scope of strictness to just the (generated) function:

    import Backbone = require('backbone');
    "use strict";
    class MyClass extends Backbone.View<Backbone.Model> { }
    export = MyClass;
    

    In practise, it makes little difference in your case as it is only difference between the strict declaration including the auto-generated "extends" code or not - and the auto-generated code is strict-compliant.