Marc Dix
Marc Dix

Reputation: 1969

Typescript - type definition for own classes without importing them

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

Answers (1)

Remo H. Jansen
Remo H. Jansen

Reputation: 25029

How about declaring interfaces?

interfaces.d.ts

interface IMainHelper {
    //... 
}

main_helper.ts

class MainHelper implements IMainHelper {
    //... 
}

other_file.ts

/// <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.

Update

I just tried and if you have two files:

test1.ts

class MainHelper {

}

var Injector = {
    injectMainHelper: function() {
        return new MainHelper();
    }
}

export default Injector;

test2.ts

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

Related Questions