Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 828
Titulum Avatar asked Dec 18 '17 21:12

Titulum


1 Answers

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");
like image 50
Titulum Avatar answered Nov 15 '22 04:11

Titulum