1

Can I convert this class definition to a constructor function while still using TypeScript?

class Animal {
  constructor(public name: string, public energy: string) {}
}
muhsen97
  • 77
  • 6
  • 1
    This isn't really possible without fighting against the TypeScript type checker, see the answer to the linked question. You could use type assertions like [this](https://tsplay.dev/mZGLaW) but you completely lose type safety. I'm not sure why you want this; what's the use case? There might be a better alternative depending on what the underlying need is. – jcalz Jun 03 '22 at 16:50
  • I just wanted to know this out of curiousity, since one of the purpose to create TypeScript was to create classes that revolve around JavaScript's prototypal inheritance system. Thank you for the link, much appreciated! – muhsen97 Jun 03 '22 at 17:33

1 Answers1

0

You could have a function that returns a new animal. This doesn't have to be part of a class, since you can have stand alone functions in TypeScript.

function CreateAnimal(name: string, energy: string): Animal
{
   return new Animal(name, energy)
}
Stewart
  • 705
  • 3
  • 6