Search code examples
typescriptmodulecommonjs

confused about typescript modules


i have module file:

// class.ts
export default class MyClass {}
module.exports = MyClass // for importing in node.js withous require('./module').default

when i import this in node.js, it works:

// class-user.js
const Class = require('./class')
const a = new Class() // alright

but when i try to use this in typescript:

// class-user.ts
import Class from './class'
// class === undefined

// but

import * as Class from './class'
const a = new Class()
// a is instance of Class, but
// [ts] Cannot use 'new' with an expression whose type lacks a call or construct signature.

Solution

  • Your problem is here:

    module.exports = MyClass
    

    It overwrites your default export.

    Use this code for class.ts:

    // class.ts
    class MyClass {}
    export = MyClass
    

    Then, to use it:

    // class-user.ts
    import * as Class from './class'
    const a = new Class()
    

    Notice: You can't use default and export = on the same module.