简体   繁体   中英

From Typescript to Javascript

I have a ts code that was translated in js and now i want to use instantiate objects from the generated js code but i am having the error "object" not defined.

For example the class in ts look like this:

class Person{
    name: string;

    constructor(name: string){
        this.name = name;
  }
/*...*/
}

And the generated js:

class Person{    
    constructor(name){
        this.name = name;
  }
/*...*/
}

now to used the object Person i did something like this:

var bob = new Person("bob");

But i am getting the error: Person is not defined .

 class Person { constructor(name) { this.name = name; } } var bob = new Person("bob"); console.log(bob); 

So your class declaration and the code that references it are in different files (from your comments).

Hence, you should require the class to use it like this:

const Person = require('./Person.js')

And in the file with the class declaration you should export it like this (in the end):

module.exports = Person

The above is node module syntax. Google "browser modules" if you work on browser code.

But the real question: Why you work on .js files when you have .ts ones? With TS you could use modern modules syntax . And it would work in browser or in node, if your TS configured properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM