Consider the following example:
class A {
private constructor(public n: number) {}
public getDouble() {
return this.n * 2;
}
static from(s: string): A;
static from(n: number): A;
static from(n1: number, n2: number): A;
static from(...args: unknown[]): A {
if (args.length === 1) {
if (typeof args[0] === 'string') {
if (args[0].length !== 1) {
throw new Error('String must have a length of 1')
}
return new A(Number(args[0]));
} else if (typeof args[0] === 'number') {
if (args[0] > 9) {
throw new Error('Number must be lower than 10')
}
return new A(args[0]);
}
} else if (args.length === 2) {
if (typeof args[0] === 'number' && typeof args[1] === 'number') {
const sum = args[0] + args[1];
if (sum > 9) {
throw new Error('Sum of numbers must be lower than 10')
}
return new A(sum);
}
}
throw new Error('No overload matched')
}
}
An instance of A
can only be constructed using the static method from
, which is overloaded to take either a string, a number or two numbers. Valid arguments only include strings of length 1, numbers below 10, and pairs of numbers the sum of which is lower than 10 - others result in an error.
I would like to implement another static method validate
, which would check if an instance of A
can be constructed from a given list of arguments, like this:
static validate(...args: Parameters<typeof A.from>): boolean {
try {
A.from(...args);
return true;
} catch (error) {
return false;
}
}
The problem is that Parameters<typeof A.from>
resolves to the parameters of the last overload in the list, in this case n1: number, n2: number
, which causes TypeScript to not allow calls with any other overload signatures, i.e. A.validate('foo')
.
How can I make TypeScript understand that validate
can be called with the same overload signatures as from
?
I have found two possible solutions but both have heavy drawbacks:
- I could manually construct another overload signature matching all previous overloads and put it at the end of the list. However, that would be rather difficult to maintain and would mess with IntelliSense hints.
- Like 1., but the signature would allow
...args: unknown[]
. This would however make TypeScript think thatfrom
actually can be called with any arguments when it can not. - I could copy and paste all the
from
overload signatures and declare them forvalidate
as well. Again, difficult to maintain - the actual use case involves a lot more overloads as well as more than one static method mimicing thefrom
overloads, which would result in 50+ lines of overload declarations.
Is there any other way to solve this? Is there a way to write an OverloadParameters
type?