0

How can I define multiple constructors in typescript? For example, I want to have the following code:

class Folder extends Asset {
 constructor(repositoryId: string, assetId: string) {
        super();
 }
 
 constructor (folder: Folder) {
 }
}

Is it possible to instantiate a class multiple ways in typescript?

Chris Hansen
  • 7,813
  • 15
  • 81
  • 165
  • 1
    Does this answer your question? [Constructor overload in TypeScript](https://stackoverflow.com/questions/12702548/constructor-overload-in-typescript) – Batajus Dec 22 '21 at 14:39
  • 1
    You can have multiple overloads "on type" level, but only single implementation allowed. (It will need to be able to handle `string | Folder` as a first parameter) https://www.typescriptlang.org/play?#code/MYGwhgzhAEAa0G8BQ1rAPYDsIBcBOArsDungBRgBcmBAtgEYCmeAlCmlrocaRZVwEtMAczaoM2fERLkqgkdAA+0Gg2YtE7VAIBm0MjgCeAB0bo9YaAF4b0AOTzhdjclRuO2dCEYA6EOmEyACIAEXRoCHRaRhwACyFhaAB3ATiI-ASggBpoMDE3AF9oRhAIRk13cU4vX39A0PDI6LiE5NTYlTomPGzc-NQC9kGCoA – Aleksey L. Dec 22 '21 at 14:45

1 Answers1

2

You trt somenthing like this:

class Folder extends Asset {
  constructor(repositoryId: string, assetId: string);
  constructor(folder: Folder);
  constructor(repositoryId?: string, assetId?: string, folder?: Folder)
    if (!folder && repositoryId && assetId) super();
    else {
      // To stuff
    }
  }
}
th3g3ntl3man
  • 1,926
  • 5
  • 29
  • 50