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

Optional arguments due to multiple constructors are not considered when resolving rest parameters in generics #38211

Closed
stephanemagnenat opened this issue Apr 27, 2020 · 2 comments
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@stephanemagnenat
Copy link

TypeScript Version: 3.8.3 and nightly from the playground as of today.

Search Terms: label:bug constructor rest parameter

Code

class A {
	constructor(value: number);
	constructor(sKey: string, sValue: string);
	constructor(sKeyOrValue: string | number, sValue?: string) {}
}

function test<T, S, A extends any[]>(ctor: new (...args: A) => T, ...params: A): T {
	return new ctor(...params);
}

test(A, 3);

Expected behavior:
I would expect this to compile without error, because class A has a valid constructor with one argument of type number.

Actual behavior:
Error: Expected 3 arguments, but got 2.(2554). It seems the compiler is not able to realise that class A has a matching constructor.

Playground Link: Playground link

Related Issues: #37142, #29707

@jcalz
Copy link
Contributor

jcalz commented Apr 27, 2020

This is a design limitation: type inference from a type with multiple call or construct signatures only happens against the last such signature. See #32418, #35641, probably others...

@ahejlsberg
Copy link
Member

Meanwhile, it works if you write it like this, though you loose the descriptive parameter names:

class A {
	constructor(...args: [number] | [string, string]);
	constructor(sKeyOrValue: string | number, sValue?: string) {}
}

function test<T, S, A extends any[]>(ctor: new (...args: A) => T, ...params: A): T {
	return new ctor(...params);
}

test(A, 3);
test(A, 'foo', 'bar');

@ahejlsberg ahejlsberg added the Design Limitation Constraints of the existing architecture prevent this from being fixed label Apr 27, 2020
@RyanCavanaugh RyanCavanaugh added Design Limitation Constraints of the existing architecture prevent this from being fixed and removed Design Limitation Constraints of the existing architecture prevent this from being fixed labels May 1, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

4 participants