3

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

2
  • if you want to use your extended class you need to call: var trueDateObject = new TrueDate("date-string") Commented Nov 30, 2015 at 20:23
  • It's a typo. I call: var trueDateObj = new trueDate("date-string") Commented Nov 30, 2015 at 20:27

1 Answer 1

1

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.

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

1 Comment

Thanks. I create wrapper class.

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.