Skip to content

Ability to access the type of a class outside the lexical scope it's defined in #6179

Closed
@thorn0

Description

@thorn0

It's common and idiomatic in Angular 1.x apps to have code like this:

angular.module('app').factory('MyService', function(service1, service2) {
    class MyService {
        constructor() {
            this.foo = 2;
        }
        bar() {
            return service1(this.foo, service2);
        }
    }
    MyService.id = Math.random();
    return MyService;
});

Defining classes this way (using a factory function with dependencies injected to it as its parameters) is often the right thing to do from the point of view of Angular's approach to dependency injection because:

  1. In its methods, the class can use dependencies provided by the container (service1, service2).
  2. The class can have static properties (MyService.id) that, ideally, shouldn't be shared between different instances of the container.

However, this code can't be ported easily to TypeScript as the type MyService isn't visible for the rest of the app. We have to define also an interface for it and remember to change the interface every time the class is changed. I wish there were a way to make such types visible globally. Can't think of a good keyword for this. Probably, public or global will do.

angular.module('app').factory('MyService', function(service1: Service1, service2: Service2) {
    public class MyService {
        foo: number;
        constructor() {
            this.foo = 2;
        }
        bar() {
            return service1(this.foo, service2);
        }
    }
    // ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it adds

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions