Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use JavaScript class in TypeScript

I have a problem introducing TypeScript to our JavaScript project. First I want to use TypeScript only in my part of the code, leaving the JavaScript untouched.

Now I try to use a JavaScript class in my TypeScript code, but I don't find a solution in the last days.

The head of my TypeScript class with import of the JavaScript:

import { BaseLogic } from "../baseLogic";
export class ClaimLogic extends BaseLogic {
...

The JavaScript class ("baseLogic.js"):

module.exports = class BaseLogic {
    constructor(meta, logger) {
    ...

My *.d.ts file ("baseLogic.d.ts"):

export class BaseLogic {
    meta: any;
    log: any;

    constructor(meta: any, logger: any)
}

The head of the compiled JavaScript:

const baseLogic_1 = require("../baseLogic");
class ClaimLogic extends baseLogic_1.BaseLogic {
...

As you see in the compiled JavaScript baseLogic_1.BaseLogic is used. This results in following error:

TypeError: Class extends value undefined is not a constructor or null

With only baseLogic_1 after the extends keyword in the JavaScript file all is fine.

I have no idea about a solution and hope you can help me!

like image 652
JulianG Avatar asked Aug 18 '17 08:08

JulianG


People also ask

Can you use JavaScript in TypeScript?

You can use thousands of existing JavaScript libraries in your TypeScript project. Type definition files allow you to enjoy the type-checking and autocomplete features in libraries that were written in JavaScript. These files make you more productive in writing code.

Should I use class in TypeScript?

When should we use classes and interfaces? If you want to create and pass a type-checked class object, you should use TypeScript classes. If you need to work without creating an object, an interface is best for you.

Can I use TypeScript class in JavaScript?

You can have typescript compile javascript files as well using 'allowJs' (in tsconfig. json). That way, you can reference typescript classes from your javascript.


2 Answers

Your import suppose to be import * as BaseLogic from "../baseLogic";.

In that way you will get the Class that you put on module.exports.

like image 130
felixmosh Avatar answered Oct 15 '22 10:10

felixmosh


The codesnipet in baseLogic.js exports the class.

module.exports = class BaseLogic {
  constructor(meta, logger) {
  ...
}

You try to access with class ClaimLogic extends baseLogic_1.BaseLogic an object that includes the class BaseLogic

Solution

import BaseLogic from '../baseLogic'
// or:  const BaseLogic = require("../baseLogic");

class ClaimLogic extends BaseLogic {
  ...
}
like image 34
Roman Avatar answered Oct 15 '22 10:10

Roman