Skip to content

Support for a built-in "constructable" type or "class type" #17572

@noemi-salaun

Description

@noemi-salaun

TypeScript Version: 2.4.0

It would be interesting to allow type hinting for class type.

Something like

function generateMyClass(myClass: class) {
    return new myClass();
}

class Foo {}

generateMyClass(Foo); // Should work
generateMyClass('something else'); // should NOT work

Currently, the closest we have is

type Instantiable = {new(...args: any[]): any};

function doSomethingWithMyClass(myClass: Instantiable ) {
    // some code that doesn't matter
}

class Foo {}
abstract class Bar {}

doSomethingWithMyClass(Foo); // It works :)
doSomethingWithMyClass('something else' ); // It doesn't work and it's OK
doSomethingWithMyClass(Bar); // It doesn't work and it's NOT OK

It is of course logical that the abstract class causes an error with the code above, this is why it could be nice to have something to handle this case.

To go further, we can think about adding some genericity on it.

// With the actual implementation
type Instantiable<T = any> = {new(...args: any[]): T};
function foo<T>(myClass: Instantiable<T>): T { /* ... */ }

// With the new class type hint
function foo<T>(myClass: class<T>): T { /* ... */ }

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions