Typescript: how to import a class from a javascript file?

后端 未结 2 1566
执笔经年
执笔经年 2021-01-02 05:25

I would like to :

  • Import a js file that defines a class: ./myClass/index.js
  • Declare the public methods of MyClass somewhere
相关标签:
2条回答
  • 2021-01-02 05:41

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

    "use strict";
    class MyClass {
      hello(name) {
        console.log(`Hello ${name}`);
      }
    
    }
    exports.default = MyClass;
    

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

    export default class MyClass {
      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");
    
    0 讨论(0)
  • 2021-01-02 05:47

    at the end of the your javascript file , write this

    exports.MyClass = MyClass;
    

    in ts files

    import * as  IzendaSynergy  from './izenda/izenda_ui.js';
    

    or

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

    in tsconfig.json file

      "allowJs": true
    
    0 讨论(0)
提交回复
热议问题