microsoft / microsoft/TypeScript

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

Open
#17,572 13 comments 52 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

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 { /* ... */ }

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the issue's proposed constructable or class-type syntax and its examples, then trace how TypeScript currently models constructor signatures and abstract classes. The payload names no files, tests, or entry points, so the implementation path and completion criteria need to be established before work begins.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.