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?

4
  • What about just omitting the new? Commented Oct 31, 2016 at 11:34
  • @GünterZöchbauer I still get the same error. Commented Oct 31, 2016 at 11:41
  • Seems Grezegorz approach should work stackoverflow.com/questions/27417107/… Commented Oct 31, 2016 at 11:42
  • Note that JavaScript doesn't really have classes even in ES 6, its just syntactic sugar over the regular patterns. You can still mess with Person.prototype even in ES 6. Commented Oct 31, 2016 at 11:43

2 Answers 2

12

Maybe try

declare var Person:any; // Magic
var john = new Person('John Doe', 22);
Sign up to request clarification or add additional context in comments.

Comments

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.