0

I've been searching for a way to implement multiple constructors of a class. I found this Stackoverflow question on constructor overload and the first answer explains that you can define multiple constructors in a class and then provide one general constructor that handles all the cases.

However, I've been snooping around in lib.es5.d.ts to see how they did it with Array. I found this interface in there:

interface ArrayConstructor {
    new(arrayLength?: number): any[];
    new <T>(arrayLength: number): T[];
    new <T>(...items: T[]): T[];
    (arrayLength?: number): any[];
    <T>(arrayLength: number): T[];
    <T>(...items: T[]): T[];
    isArray(arg: any): arg is any[];
    readonly prototype: any[];
}

and

declare var Array: ArrayConstructor;

Then I saw in other es5 files that they can do like

const array = new Array();
const array = new Array(4);
const array = new Array([{ id: 5 }]);

So I would expect that somewhere there is some code like

class Array {
    constructor() {

    }
}

where the constructor implementation is defined. But of course, Array is already declared as a global "var", so you can't create a class with it (I tried this with my own class and interface with constructors).

So then how can you apply the declared constructors in the Interface if you cannot create the class and implement those constructors? How are they able to do "new Array(input)" and apply this ArrayConstructor interface?

CoderApprentice
  • 425
  • 1
  • 6
  • 21
  • It's unclear what you're asking for. Are you looking for the [`implements`](https://www.typescriptlang.org/docs/handbook/interfaces.html#implementing-an-interface) keyword? – Chase Jan 12 '21 at 13:47
  • 2
    note that the standard library is not rewritten in typescript. It's just javascript - the types of them are provided in separate declaration files. Which is why it needs to do `declare var Array: ArrayConstructor` instead of `implements`. You don't need to make a declaration file in the same manner if your own code is being written directly with typescript. – Chase Jan 12 '21 at 13:48

0 Answers0