简体   繁体   中英

How to extend an ES6 class in a TypeScript class

I have a JavaScript class written in ES6:

// MyClass.js
export default class MyClass {
  myfunction() {
    console.log('myfunction called');
  }
}

I'd like to extend this class with a TypeScript class:

// MyTSClass.ts
import MyClass from './MyClass';

class MyTSClass extends MyClass {
  public initialize() {
    this.myfunction();
  }
}

This produces a TypeScript compiler error:

TS2339: Property 'myfunction' does not exist on type 'MyTSClass'

I have esModuleInterop set to true in my tsconfig.

I attempted to make a declaration file, thinking this might help:

// MyClass.d.ts
export = MyClass;

declare class MyClass {
  myfunction: void;
}

This makes the compiler happy, but in the generated code in the browser I see something unexpected, and the console log does not print:

class MyTSClass extends WEBPACK_IMPORTED_MODULE_1__["MyClass"]...

What am I doing wrong?

It's hard to tell from the info you've provided, but I would start at whatever is calling initialize . I'm assuming you didn't mean to use constructor instead? In Chrome, you can use the debugger; statement to launch the debugger at a specific point in your code, which I think is easier than setting breakpoints. From there, you can step through the code and see what's going on. You could also console.log the instance of your class to inspect its prototype chain to make sure the myfunction method is there.

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