admin管理员组

文章数量:1305583

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 ponent written in TypeScript. Normally, I would simply instantiate it like this:

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

When piling 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?

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 ponent written in TypeScript. Normally, I would simply instantiate it like this:

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

When piling 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?

Share Improve this question asked Oct 31, 2016 at 11:26 Tudor CiotlosTudor Ciotlos 1,8455 gold badges30 silver badges47 bronze badges 4
  • What about just omitting the new? – Günter Zöchbauer Commented Oct 31, 2016 at 11:34
  • @GünterZöchbauer I still get the same error. – Tudor Ciotlos Commented Oct 31, 2016 at 11:41
  • Seems Grezegorz approach should work stackoverflow./questions/27417107/… – Günter Zöchbauer 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. – Jared Smith Commented Oct 31, 2016 at 11:43
Add a ment  | 

2 Answers 2

Reset to default 12

Maybe try

declare var Person:any; // Magic
var john = new Person('John Doe', 22);

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

本文标签: angularIs it possible to instantiate a JavaScript object in TypeScriptStack Overflow