Skip to content

Extracting the instance type from the ctor value that works for abstract classes #26829

Closed

Description

@rkirov

Search Terms

abstract class constructor type

Suggestion

Currently, I think there is no way to express the type of constructor functions for abstract classes. On one hand that is correct because 'new' cannot be called on them. However, sometimes there is a need to tie an instance of the abstract class with the constructor function for type-checking.

Use Cases

DI helper functions in angular and other frameworks.

Examples

// Angular calls this Type<T>
// https://github.com/angular/angular/blob/master/packages/core/src/type.ts#L25
interface Factory<T> extends Function {
  new (...args: any[]): T;
}

abstract class AC {
  abstract x: number;
}

class C extends AC {
  x = 0;
}

// a DI-like system, that returns instance of C for get(C) and get(AC).
// The mechanism is left unspecified.
declare function get<T>(token: Factory<T>): T;

let x1 = get(C);
let x2 = get(AC);  // error, underlying issue is that AC is not assignable to Factory<AC>

Basically, this is asking for a mechanism to go from a value C, where C is a symbol for a class (abstract or not), to the type C.

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. new expression-level syntax)

Activity

  1. mattmccutchen commented on Sep 3, 2018

    @mattmccutchen
    Contributor

    Could you just use the prototype?

    interface Factory<T> extends Function {
      prototype: T;
    }

    This doesn't work for generic classes, but I'm not sure how your proposal could either.

  2. rkirov commented on Sep 18, 2018

    @rkirov
    ContributorAuthor

    Closing this issue in favor of #24428. In practice both AngularJS and Angular DI types are written using an second overload to :any to handle the cases where the issue described above prevents from type checking :/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions