Skip to content

No way to get constructor arguments for abstract class? #41819

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

Closed
Griffork opened this issue Dec 4, 2020 · 3 comments
Closed

No way to get constructor arguments for abstract class? #41819

Griffork opened this issue Dec 4, 2020 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@Griffork
Copy link

Griffork commented Dec 4, 2020

TypeScript Version: 4.0.3

Search Terms:
Infer arguments from constructor of abstract class.

Code

I have the following class, I cannot get the constructor parameters via generic typing.

abstract class Test {
    constructor(public a: string, public b: number) {}
}

Abstract classes cannot be assigned to new:

type ObjectType<T> = T extends (new (...args: any[]) => infer C) ? C : never;
type ConstructArguments<T> = T extends (new (...args: infer C) => any) ? C : never;

declare function ClassWrapper<
	Class extends (new (...args: any[]) => any),
	Output extends ObjectType<Class>,
	ConstructorArgs extends ConstructArguments<Class>>
	(base: Class): (
			(new (...args: ConstructorArgs) => {c: string} & Output));

var test = ClassWrapper(Test); //Error about abstract class not being able to be assigned to new(): Test

Constructor arguments can not be inferred via crawling the prototype:

type AbstractConstructArguments<T> = T extends {prototype:{constructor: (...args: infer C)=>any}}?C: never;

var args: AbstractConstructArguments<Test>;  //args is never.

Expected behavior:
There should be a way to type the constructor arguments for an abstract class. Either the class is assignable to new or inferring the arguments from the constructor directly should result in valid arguments and not type never.

Actual behavior:
ClassWrapper(Test) throws an error.
AbstractConstructArguments always returns type never.

Playground Link

Related Issues:

https://stackoverflow.com/questions/57643184/infer-arguments-for-abstract-class-in-typescript

@RyanCavanaugh
Copy link
Member

See #36392

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Dec 4, 2020
@RyanCavanaugh
Copy link
Member

Or #35576

@Griffork
Copy link
Author

Griffork commented Dec 5, 2020

Thanks Ryan. I swear I searched for it, I think since I used the infer and arguments keywords those issues got buried in a bunch of unrelated stuff 😕

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants