1

I have an interface:

interface I {
    new(name: string, ...args: any[]);
}

And classes with constructors like this:

constructor(name: string) { }
constructor(name: string, a: number) { }
constructor(name: string, a: string, b: string, c: string, d: string) { }
constructor(name: string, x: { b: boolean }) { }

It always tells me the implementation does not fit the interface.

I thought it would be sufficient to use , ...args: any[] but it's not.

This is a syntax error: , ...args?: any[].

Even when I have all rest arguments optional, like explained in this answer it yield the same error:

constructor(name: string, a?, b?, c?) { }

In one of those answers, someone advices to just not use a constructor prototype in the interface (yes, I also tried overloading without success). But it would be nice to have a constructor interface with at least this name: string and the rest to be optional.

How can I have constructors with 1 mandatory and 0-n optional arguments?

Community
  • 1
  • 1
Daniel W.
  • 31,164
  • 13
  • 93
  • 151
  • I don't think you can define a constructor signature in your interface. At least not like that. Check this answer here: http://stackoverflow.com/a/13408029/2300664 – Seamus Feb 24 '17 at 15:01
  • 1
    Also this: https://www.typescriptlang.org/docs/handbook/interfaces.html#difference-between-the-static-and-instance-sides-of-classes – Seamus Feb 24 '17 at 15:04

1 Answers1

1

@Seamus gave you correct answer. You cant implement static properties of the class defined in interface. But you can still check against them. Read the links he provided - they explain the issue quite well.

I can't post a link to more detailed example in the comments so I post it here: playground example

Amid
  • 21,508
  • 5
  • 57
  • 54