1

An AngularJS component in TypeScript:

class MyComponentCtrl {
    static $inject = ['MyService'];
    constructor(private MyService) {
      MyService.testfn(55); // No error in typescript
    }
}

class MyComponent implements ng.IComponentOptions {
    constructor() {
        this.controller = MyComponentCtrl;
        this.template = 'hello';
    }
}

angular
    .module('app')
    .component('MyComponent', new MyComponent());

An AngularJS service in TypeScript:

class MyService {
    constructor() {

    }

    public testfn(age: number) {
        console.log(age);
    }
}

angular
    .module('app')
    .service('MyService', MyService);

When I hit Cmd + Click on the testfn in WebStorm, it's not found ("No decleration to go to"). Also, the TypeScript compiler is not giving error when I use testfn with invalid argument.

When I click on MyService in static $inject WebStorm finds it correctly.

Can I structure this differently somehow so WebStorm and TypeScript finds it?

1 Answer 1

1

Injected MyService is any, so it doesn't cause type error.

It's impossible for IDE or TypeScript to determine that it is an instance of MyService service. Also, injecting it as MyService is misleading, because it's class instance, not a class itself.

A class should be exported:

export class MyService {...}

It should be imported and specified as injected service type:

class MyComponentCtrl {
    static $inject = ['MyService'];
    constructor(private myService: MyService) {
      myService.testfn(55);
    }
}
Sign up to request clarification or add additional context in comments.

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.