5

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:

  1. 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.
  2. Like 1., but the signature would allow ...args: unknown[]. This would however make TypeScript think that from actually can be called with any arguments when it can not.
  3. I could copy and paste all the from overload signatures and declare them for validate as well. Again, difficult to maintain - the actual use case involves a lot more overloads as well as more than one static method mimicing the from 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?

2 Answers 2

4

If you have an overloaded function/method where every single call signature has the same return type (as is the case for from() where the return type is always A), you can refactor the function to a version with a single call signature with a rest parameter whose type is a a union of rest tuples:

static from(...args: [s: string] | [n: number] | [n1: number, n2: number]): A {
  // same impl as before
}  

This is callable exactly as before:

A.from("okay"); // works
A.from(1); // okay
A.from(2, 4); // okay
A.from("oops", 2); // error!

In fact, it even looks like an overloaded function from the point of view of IntelliSense:

/* A.from(⎀) */
// 1/3 from(s: string): A
// 2/3 from(n: number): A
// 3/3 from(n1: number, n2: number): A

But crucially, Parameters<typeof A["from"]> is now the full union of tuples and does not lose any information:

static validate(...args: Parameters<typeof A.from>): boolean {
  // same impl as before
}

and you can verify that A.validate() can be called in exactly the same ways as A.from():

A.validate("okay"); // works
A.validate(1); // okay
A.validate(2, 4); // okay
A.validate("oops", 2); // error!

Playground link to code

0

I have found a workaround based on solution number 3. I tried to figure out if there's a way to declare multiple members that share the same list of overloads. It's not pretty but I do not believe there exists a more elegant way to handle this.

The solution involves converting the class into a typed class expression and writing a generic type for the overload. Continuing the example from the question, the overload type would look like this:

type MyOverload<ReturnType> = {
  (s: string): ReturnType;
  (n: number): ReturnType;
  (n1: number, n2: number): ReturnType;
}

Then we declare an interface for the class and its constructor:

interface AInterface {
  getDouble(): number;
}

interface AConstructor {
  new (n: number): AInterface;
  from: MyOverload<AInterface>;
  validate: MyOverload<boolean>;
}

And finally the class implementation, without declaring overloads:

const A: AConstructor = class A implements AInterface {
  constructor(public n: number) {}
  static from(...args: unknown[]): A {
    // same as before
  }
  static validate(...args: unknown[]): boolean {
    try {
      A.from(...args);
      return true;
    } catch (error) {
      return false;
    }
  }
}

What this achieves:

  • You can declare multiple methods with the same list of overload parameters but different return types.
  • Their call signatures will be typed correctly and work with IntelliSense.

Limitations (as far as I am aware):

  • You need to declare the public side of the class in the interfaces and then redeclare and implement it in the class, and keep those two declarations in sync. This is obviously an advantage for overloaded methods, but not so much for the other ones, and would be a burden on maintenance.
  • No protected members, neither instance nor static (because interfaces and types cannot declare private/protected members).
  • Supplying additional arguments to the overloaded methods will be clunky.

You could further generalize the overload type to take an additional argument or multiple (i.e. for a method like createAndMultiplyBy):

type MyOverload<ReturnType, MethodArg = never> = {
  (s: string, arg: MethodArg): ReturnType;
  (n: number,  arg: MethodArg): ReturnType;
  (n1: number, n2: number, arg: MethodArg): ReturnType;
}

And then declare the method as createAndMultiply: MyOverload<number, number>. The extra arguments wouldn't get names though, and if there were multiple (i.e. type MyOverload<ReturnType, MethodArgs extends any[] = never>) then IntelliSense would have to show them as, for MyOverload<any, [number, number]> - (s: string, ...args: [number, number]).

For my use case these additional overloaded methods were supposed to be just an extra layer of sugary utility. I decided that the overhead of maintaining those extra interfaces was not worth it, and gave up on implementing them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.