Skip to content Skip to sidebar Skip to footer

Typescript: How To Import A Class From A Javascript File?

I would like to : Import a js file that defines a class: ./myClass/index.js Declare the public methods of MyClass somewhere (in index.ts or a specified declaration file, I really

Solution 1:

There is no export default class in JavaScript. What you can do is write your JS file like this. myClass/index.js

"use strict";
classMyClass {
  hello(name) {
    console.log(`Hello ${name}`);
  }

}
exports.default = MyClass;

Create a Type definitions for it. myClass/index.d.ts

exportdefaultclassMyClass {
  hello(name: string): void;
}

You can then import it into your TypeScript like this.

///<reference path="./myClass/index.d.ts" />
import MyClass from"./myClass";

const my = new MyClass();
my.hello("Stack Overflow");

Solution 2:

at the end of the your javascript file , write this

exports.MyClass = MyClass;

in ts files

import * asIzendaSynergyfrom'./izenda/izenda_ui.js';

or

import { IzendaSynergy } from'./izenda/izenda_ui.js';

in tsconfig.json file

"allowJs":true

Post a Comment for "Typescript: How To Import A Class From A Javascript File?"