1

I'm using the JS Module pattern (as described in this post), and I have code that looks like this:

Foo = (function($, ko) {

    //Constructor for Foo
    var Foo = function () {
        //Uses $ and ko
    };
    return Foo;

})($, ko)

I want to convert this pattern to a TypeScript equivalent, but I'm not sure what that would be. Do I replace the whole IIFE with this?

 class Foo {
     constructor() {
         //Uses $ and ko
     }
 }

That seems roughly equivalent, but then it loses the explicit injection of my dependencies. Is this the way to do this in TypeScript?

2 Answers 2

1

Typescript is a superset of JavaScript, so your JavaScript code is valid TypeScript. The code below compiles to the exact same JavaScript;

var $, ko;
var Foo = (function($, ko) {

    //Constructor for Foo
    var Foo = function () {
        //Uses $ and ko
    };
    return Foo;

})($, ko)

var theFoo = new Foo();

Alternatively, if you want to use TypeScript classes, you can pass values to the constructor in TypeScript;

var $, ko;
class Foo {
    constructor($, ko) {
     //Uses $ and ko
    }
}

var theFoo = new Foo($, ko);

Produces this Javascript:

var $, ko;
var Foo = (function () {
    function Foo($, ko) {
        //Uses $ and ko
    }
    return Foo;
})();
var theFoo = new Foo($, ko);

That is not directly equivalent to your original code, but it may serve the purpose.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah; I don't want my libraries to be arguments to every object that I construct. My goal here isn't to construct a single object, it's to use this module to define a constructor that other modules can use, without forcing the other modules to provide me all my libraries every time they construct an object.
And, yes, I'm aware that my existing code is still "legal typescript"; but the point is that I want to use typescript so that my Foo objects all have a consistent interface.
0
 import $ = require("../vendor/jquery")

This is what you're looking for?

One thing to remember is that any JavaScript code is valid TypeScript code. Use jQuery the way you used to and it will work just fine. Otherwise you need to be more specific.

1 Comment

This isn't true at all. Try compiling var x = { foo: 5 }; x.bar = "yes";

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.