Reputation: 1969
I'm using dependency injection with typescript, means that I can create an object in a module without importing the class (I'm importing an Injector instead which gives me the object instance I need). If I now want to provide a type for the receiving variable, I get a Unresolved type
error. Any good solution for that?
Example
An object of type 'MainHelper' is returned by Injector.injectMainHelper();
but the type is unknown to the current module, because I haven't imported MainHelper
(and I don't want to import it).
let mainHelper:MainHelper = Injector.injectMainHelper();
You can check the full code here.
Upvotes: 3
Views: 1583
Reputation: 25029
How about declaring interfaces?
interface IMainHelper {
//...
}
class MainHelper implements IMainHelper {
//...
}
/// <reference path="./interfaces.d.ts" />
import Injector from "./injector";
let mainHelper: IMainHelper = Injector.injectMainHelper();
Note: If you add the reference to your tsconfig.json
you won't need to add it in the file.
I just tried and if you have two files:
class MainHelper {
}
var Injector = {
injectMainHelper: function() {
return new MainHelper();
}
}
export default Injector;
import Injector from "./test1";
let mainHelper = Injector.injectMainHelper(); // mainHelper is MainHelper
TypeScript is able to infer the type of mainHelper
. If you don't add the type the compiler will automatically detect its type.
If you have something more generic like:
var Injector = {
injectSomething: function(somethingID) {
// find something and dependencies
return new Something(..dependencies);
}
}
The solution would be to use generics:
let mainHelper = Injector.injectSomething<MainHelper>("mainHelperID");
But in that case you will need interfaces once more...
Upvotes: 2