4

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?

1
  • 1
    You can do so, but create a javascript file to store that function and a declaration file to declare the function as class, then typescript will not throw error Commented May 27, 2019 at 16:05

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

what should be tsconfig? I do this but still I get error
@canbax - If the numble.d.ts file is alongside your other .ts files, in my experience it just gets picked up. That's described here. This may also be useful. So I think you just need to make sure that TypeScript is including the .d.ts file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.