Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript class extends JavaScript function

Tags:

typescript

I wanted to create a new class extending from an existing class-like JavaScript function

function MyFunctionClass() { }

MyFunctionClass.prototype.myMethod = function(str) {
  console.log(str);
};

I wrote this simple piece of code

class Test extends MyFunctionClass {
    constructor() {
        super();
    }
}

let t = new Test();
t.myMethod('Test');

And surprisingly it does work, as it prints Test and no runtime errors are raised.
However, the TypeScript playground tells me

Type '() => void' is not a constructor function type.

Can I safely ignore this error and use that code in production?

like image 518
LppEdd Avatar asked Sep 15 '25 03:09

LppEdd


1 Answers

To do that, you'd create a TypeScript declaration file (mumble.d.ts) to provide TypeScript with the information about the class, for instance:

// In a .d.ts file associated with the project
declare class MyFunctionClass {
  myMethod(str: string): void;
}

That way, not only does TypeScript know that MyFunctionClass is a class, it also knows that myMethod expects a string and doesn't have a return value.

And surprisingly it does work...

It's not surprising. :-) Remember that TypeScript compiles to JavaScript. If you're targeting ES5, TypeScript's class construct compiles to a JavaScript constructor function and associated prototype, which TypeScript can hook up in an inheritance relationship with the JavaScript MyFunctionClass. If you're targeting ES2015+, TypeScript's class compiles to a ES2015+ class, and ES2015+ class can use an ES5-style constructor function in the extends clause.

like image 132
T.J. Crowder Avatar answered Sep 17 '25 18:09

T.J. Crowder