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
2 Answers
Reset to default 12Maybe 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
版权声明:本文标题:angular - Is it possible to instantiate a JavaScript object in TypeScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741806814a2398554.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论