Skip to content

Introduce Class or Constructor utility typeΒ #56286

Closed as not planned
Closed as not planned
@DanKing123

Description

@DanKing123

πŸ” Search Terms

Class Constructor utility type

βœ… Viability Checklist

  • 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. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals

⭐ Suggestion

Angular includes a Type utility type which is defined like this:

export declare interface Type<T> extends Function {
    new (...args: any[]): T;
}

I think this could be more succinctly defined, and I think the word "Type" here is a little misleading, as this actually denotes a class/constructor.

I'm wondering though, why TypeScript doesn't have a built-in equivalent? (Or if it does, why I can't find it, and it isn't documented here: https://www.typescriptlang.org/docs/handbook/utility-types.html)

I was thinking something like this:

export type Constructor<T> = new(...args: any[]) => T;

or maybe even:

export type Class<T> = new(...args: any[]) => T;

It's easy enough to hand-roll, but just feels like something that ought to be built into the language?

πŸ“ƒ Motivating Example

This pattern is already used extensively in many on-line code examples. E.g. see here: https://dev.to/kalashin1/utility-types-in-typescript-4nfo - although this post suggests TypeScript already has this feature, whereas as far as I can tell, it actually doesn't!

πŸ’» Use Cases

I've used the Angular Type utility type quite extensively in my Angular application, whenever I want to pass around classes for some reason, whilst also keeping track of their associated instance types.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions