joonhocho / tsdef

TypeScript common pattern shortcut definitions / utility gist library

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Newable<T> to ensure parameter is a class that is non-abstract and inherits from T

Sv443 opened this issue · comments

I want to suggest a new pattern Newable<T> which I got from here.

I had the problem that I wanted to pass the class itself as the type of a parameter to a function (so I can use derived classes on this parameter), but the type of the parameter is an abstract class, so TS told me it isn't newable / it has no construct signatures (hard to explain, please look at the example).
I searched through tsdef but couldn't find something that would fix my issue (or I'm just blind, so in that case please tell me), so I searched around and found the above linked stackoverflow answer.
It would be cool if you could tell me if this can already be achieved with tsdef. If not, I'd be happy to submit a PR.

My situation:

abstract class A { }

class B extends A
{
	constructor() { super(); }
}


function test(MyClass: typeof A) // (similar error when removing typeof)
{
    let foo = new MyClass();
    //        ^^^^^^^^^^^^^
    // This expression is not constructable.
    // Type 'A' has no construct signatures.  ts(2351)
}


test(B);

Example with Newable<T>:

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


abstract class A { }

class B extends A
{
	constructor() { super(); }
}


function test(MyClass: Newable<A>)
{
    let foo = new MyClass();
    // no error
}



test(B); // works fine