Javascript TypeScript |扩展错误(未捕获的TypeError:这不是X对象)

Javascript TypeScript |扩展错误(未捕获的TypeError:这不是X对象),javascript,typescript,Javascript,Typescript,我创建这个类: 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

我创建这个类:

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)
    }
}
但是,当我对继承的类(例如:trueDateObj.getDate())调用方法时,会出现以下错误:

未捕获类型错误:这不是日期对象

输出JS代码:

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);
我创建的新对象如下所示:

var trueDateObj = new trueDate("date-string")
Firefox错误:

TypeError:对不兼容的对象调用了getDate方法

您不应该(即使不是所有情况,也不能在大多数情况下)继承本机/基元类型。即使在纯javascript中,扩展基元类型也被认为是错误的做法(阅读“错误做法:本机原型的扩展”一节来了解原因)

在这种情况下,它将不起作用,因为Date类不符合typescript中继承的工作方式


如果你想做这样的事情,你应该做的是一个包装类或使用一些已经存在的东西,比如矩.js。

如果你想使用扩展类,你需要调用:var trueDateObject=new TrueDate(“日期字符串”),这是一个输入错误。我调用:var trueDateObj=新的trueDate(“日期字符串”),谢谢。我创建了包装器类。