Tudor Ciotlos Tudor Ciotlos - 4 months ago 25
Javascript Question

Is it possible to instantiate a JavaScript object in 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 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?


Maybe try

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