Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Sv443 opened this issue Apr 1, 2021 · 0 comments

Comments

@Sv443
Copy link

Sv443 commented Apr 1, 2021

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
@Sv443 Sv443 changed the title Newable<T> to ensure a class that is non-abstract and inherits from T Newable<T> to ensure parameter is a class that is non-abstract and inherits from T Apr 1, 2021
@Sv443 Sv443 changed the title Newable<T> to ensure parameter is a class that is non-abstract and inherits from T Newable<T> to ensure parameter is a class that is non-abstract and inherits from T Apr 1, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant