Reputation: 33399
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?
Upvotes: 1
Views: 1220
Reputation: 511
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.
Upvotes: 0
Reputation: 17702
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.
Upvotes: 1