Skip to content

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

Closed
@rkirov

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)

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