简体   繁体   中英

How to use a compiled TypeScript class in Javascript

Imagine I have this simple TypeScript class, Animal.ts :

export default class Animal {
  constructor(public name : string) { }
}

With this tsconfig.json file:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true
  },
  "files": [
    "Animal"
  ]
}

How can I use the compiled version of this class (compiled by running tsc ) in a javascript file like so:

var Animal = require("./Animal");

var newAnimal = new Animal();

Should I edit something in my tsconfig.json file? The error I get is:

ReferenceError: Animal is not defined

As Shane van den Bogaard pointed out, the default keyword in Animal.ts needs to be omitted and :

const { Animal } = require('./Animal');

should be used instead of

var Animal = require('./Animal');

This way we can call the Animal class and initialize an object by using

const { Animal } = require('./Animal');
var newAnimal = new Animal("Clifford");

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