0

I'm trying to add TypeScript typings to a 3rd party JavaScript library. Most of the class methods take another instance of the same class and return a new instance, but they'll also accept the same overloaded constructor arguments in place of an actual instance of the class. I'm trying to avoid writing the same overloaded signature for each of the class's many methods but I'm not sure how exactly to do this in my .d.ts file.

For example, I could write out each one like...

class Foo {
  constructor(x: number);
  constructor(x: number, y: number);
  constructor({ x: number, y: number });

  Fizz(foo: Foo): Foo;
  Fizz(x: number): Foo;
  Fizz(x: number, y: number): Foo;
  Fizz({ x: number, y: number }): Foo;

  Buzz(foo: Foo): Foo;
  Buzz(x: number): Foo;
  Buzz(x: number, y: number): Foo;
  Buzz({ x: number, y: number }): Foo;

  // etc... for several methods
}

But it'd be preferable to do something like...

class Foo {
  constructor(x: number);
  constructor(x: number, y: number);
  constructor({ x: number, y: number });

  // I'd like some sort of syntax like...
  Fizz(constructor()): Foo;
  Buzz(constructor()): Foo;
}

Can I easily declare and reuse an overloaded method signature?

1 Answer 1

1

You can consolidate the signatures for member functions quite easily:

// Consolidate the signatures
type CreatesFoo = {
    (foo: Foo): Foo;    
    (x: number): Foo;
    (x: number, y: number): Foo;
    (obj: { x: number, y: number }): Foo;
}

class Foo {
  constructor(x: number);
  constructor(x: number, y: number);
  constructor(obj: { x: number, y: number });
  constructor(...args:any[]) {}


  Fizz: CreatesFoo = (): any => {
  }

  Buzz: CreatesFoo= (): any => {
  }

  // etc... for several methods
}

However the constructor cannot be consolidated into the same signature. The simplest method is simply to list it out as I have done 🌹

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is exactly what I was looking for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.