2

I have an existing JavaScript "class" , which is defined like this:

function Person(name, age) {
    this.name = name;
    this.age = age;
}

(I know there are no actual classes in JavaScript prior to ES6)

This class needs to be used inside a Angular2 component written in TypeScript. Normally, I would simply instantiate it like this:

var john = new Person('John Doe', 22);

When compiling the TypeScript code into JavaScript I will get an error saying Cannot find name 'Person', since Person is not a TypeScript class.

Is there any solution to use the existing JavaScript class, without rewriting it into TypeScript?

Tudor Ciotlos
  • 1,805
  • 4
  • 29
  • 47

2 Answers2

12

Maybe try

declare var Person:any; // Magic
var john = new Person('John Doe', 22);
Grzesiek
  • 715
  • 5
  • 24
0

Grzesiek's answer worked for me but I required a small modification.

My JS object was buried a couple of functions deep (to emulate namespacing) & was instantiated like:

new MyCorp.Utils.UsefulThing();

Because I had to place the declaration within a TS namespace I then had to mark it with 'export' for it to be visible to the TS code (which was in a different namespace) so I ended up with:

namespace MyCorp.Utils {
    export declare var UsefulThing: any;
}
Jon
  • 309
  • 3
  • 10