简体   繁体   中英

TypeScript | Extends error (Uncaught TypeError: this is not a X object)

I create this class:

class trueDate extends Date {
    constructor(date: string) {
        super(date)
    }

    getDay(): number {
        var day = super.getDay()
        return day === 0 ? 7 : day
    }

    addDate(date: number) {
        super.setTime(super.getTime() + date * 86400)
    }
}

But, when I call methods on an inherited class (for example: trueDateObj.getDate() ) get the error:

Uncaught TypeError: this is not a Date object.

Output JS code:

var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var trueDate = (function (_super) {
    __extends(trueDate, _super);
    function trueDate(date) {
        _super.call(this, date);
    }
    trueDate.prototype.getDay = function () {
        var day = _super.prototype.getDay.call(this);
        return day === 0 ? 7 : day;
    };
    trueDate.prototype.addDate = function (date) {
        _super.prototype.setTime.call(this, _super.prototype.getTime.call(this) + date * 86400);
    };
    return trueDate;
})(Date);

I create new object like this:

var trueDateObj = new trueDate("date-string")

Firefox error:

TypeError: getDate method called on incompatible Object

You should not (and can not in most if not all cases) inherit from native/primitive types. Extending primitive types is considered bad practice even in pure javascript (read the section 'Bad practice: Extension of native prototypes' here to learn a bit about why).

In this case it will not work because the Date class does not conform to how the inheritance works in typescript.

If you want to do something like this what you should do is a wrapper class or use something already existing, like moment.js for example.

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