3

I'm getting my butt kicked trying to use TypeScript in a functional style with dependencies. Let's say I want to make a module that depends on another module.

If I wasn't using Dependency Injection it would look like this (in node).

SomeOtherModule = require("SomeOtherModule")
exports.doSomething = function() {
  SomeOtherModule.blah()
}

This is how I do it with Dependency Injection

module.exports = function(SomeOtherModule) {
  function doSomething() {
    SomeOtherModule.blah()
  }

  return {doSomething: doSomething};
}

In typescript if you define a concrete class or module you can just type the functions as you export them or include them in the class. It's all right next to each other.

But since I can't define a module inside the DI function, the only way to do this that I can see would be to define an interface for the object I'm returning separately, which is annoying, because I want to have the type annotations in line with the definitions.

What's a better way to do this?

2 Answers 2

2

This will probably give you a good start: http://blorkfish.wordpress.com/2012/10/23/typescript-organizing-your-code-with-amd-modules-and-require-js/

I don't know if this is the best way to set it up. But I got it to work.

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

1 Comment

Yeah, I can get things to work, I'm just not happy with how it looks when I'm done. I'm going to go the route of just specifying the interface at the top for now.
0

I ended up dropping AMD on my project, since I'm also using AngularJS and they step on each other's toes. I did keep using that same DI pattern through, so it looks like this in the end.

I'm pretty happy with it. I experimenting uses classes instead (you can get really close if you keep your module stateless and have the constructor be the injector function), but I didn't like having to use this for all the dependencies.

Also, classes don't actually buy me anything, because if I were coding to an interface I'd have to define the types twice anyway.

interface IMyService {
  doSomething();
}

module.exports = function(SomeOtherModule) {

  return {doSomething: doSomething}

  function doSomething() {
    SomeOtherModule.blah()
  }
}

Comments

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.