Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 201
Tudor Ciotlos Avatar asked Jan 17 '26 15:01

Tudor Ciotlos


1 Answers

Maybe try

declare var Person:any; // Magic
var john = new Person('John Doe', 22);
like image 62
Grzesiek Avatar answered Jan 20 '26 03:01

Grzesiek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!