LppEdd
LppEdd

Reputation: 21124

TypeScript class extends JavaScript function

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?

Upvotes: 4

Views: 1499

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

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.

Upvotes: 5

Related Questions