Description
π 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.