简体   繁体   中英

require exported typescript class in javascript

I'm moving my nodejs project from Javascript to Typescript. It's going to be a slow process, slowly changing things over a few months as i need to tweak stuff.

I've created a typescript class that looks something like this:

// RedisRepository.ts

export class RedisRepository {
  public async getDevice(serial: string) : Promise<Device> {
    // blah
    return device;
  }
}

Then in another Javascript file where i need to reference and then call the functions on the above class.

// ExpressApi.js

const repository = require('../Redis/RedisRepository');

async function getRedis(req, res) {
  try {
    const device = await repository.getDevice('serialnumberxxx');
    res.status(200).end(JSON.stringify(device ));
  } catch (e) {
    logger.error(e);
    res.status(500).end();
  }
}

however, when it tried to call the function on the repository it says it doesn't exist. Using chrome debugger, i can see that it exists at: repository.RedisRepository.prototype.getDevice. This doesn't seem the correct way to use the function though.

While I appreciate I could just convert ExpressApi.js to Typescript. I'm going to have this problem with many different files. So i need to use it as JavaScript for now. I'll slowly continue to go round the project and change things to Typescript.

As @crashmstr mentioned, you should create a new instance of RedisRepository , then call getDevice method. If you still want to use

const repository = require('../Redis/RedisRepository');

syntax, you could export default new RedisRepository() from your RedisRepository.ts file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM