简体   繁体   中英

typescript - extend class definition without constructor

I'm using a library which isn't written in TypeScript and thus I've to use the definition file.

Within this definition file there's a class without a constructor (because the original JS code doesn't have a constructor). If I try to extend the class within my code, I get the error:

Error:(36, 2) TS2377: Constructors for derived classes must contain a 'super' call.

If I add super() to the constructor, JavaScript complains:

Uncaught TypeError: _super.call is not a function

How can I modify the definition file so that this code works and the first error from TS is eliminated? (for TypeScript 1.6)


Here's a simple example of the definition file (based on backbone-global.d.ts :

declare module Backbone {
    class Events {
        on(eventName: string, callback?: Function, context?: any): any;
        off(eventName?: string, callback?: Function, context?: any): any;
    }

    class ModelBase extends Events {
    ...
    }

    class Router extends Events {
    ...
    }
}

Within my code I have something like:

/// <reference path="libs/typescript/backbone/backbone.d.ts" />

class RosApiManager extends Backbone.Events {

    constructor() {
        super();
    }
}

Backbone.events is not a class (and should not have been declared as such in the .d.ts file). You can't extend something that isn't a class.

Some might the error:

_super.call is not a function

if they incorrectly defined the class like

export class InlineIf extends React{... }

instead of

export class InlineIf extends React.Component {... }

Adding this as an answer hoping someone might find it useful in the future...

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