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

后端 未结 2 1565
执笔经年
执笔经年 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.

    /// 
    import MyClass from "./myClass";
    
    const my = new MyClass();
    my.hello("Stack Overflow");
    

提交回复
热议问题