Search code examples
typescriptnpmcommonjs

Use class from CommonJS module in Typescript


I have an npm package with a file similar to this:

'use strict'

module.exports = class TModel {
  constructor (app) {
    this.app = app
  }

  static schema () {

  }
}

Which I want to use in a Typescript file like so:

import Model from 't-model';

export class Book extends Model {
    static schema() : any {
        return {
            title: {
                type: 'string'
            }
        }
    }
}

But this doesn't work. PHPStorm gives the error:

Cannot resolve file

And compiling with tsc gives me the error:

error TS2307: Cannot find module 't-model'

If use 't-model/index' instead of 't-model' PHPStorm stops giving me an error but tsc still gives the same error.

I am trying to unify packages I would make for the backend API and the frontend, which uses Typescript. Is there a way to do this?


Solution

  • have an npm package with a file similar to this:

    If this file is typescript

    instead of:

    module.exports = class TModel {
    

    Do export class TModel and let TypeScript generate the module.exports (compile with module: commonjs). This way TypeScript understands the exports

    More on this : https://basarat.gitbooks.io/typescript/content/docs/project/modules.html

    If the file is javascript

    You need to declare it:

    declare module 't-model' {
       class TModel // .....
       export = TModel;
    }
    

    More on this : https://basarat.gitbooks.io/typescript/content/docs/types/migrating.html