Factorial Factorial - 2 months ago 25
TypeScript Question

Override constructor in Date subclass

I would like to create a new

Date
descendant class and override the constructor:

export class MyDate extends Date {
constructor(str: string) {
super(str);
}
}


Now, if I create a
MyDate
object, it doesn't work :

var myDate = new MyDate("2016-10-20T12:30:00+0200");
console.log(myDate.toDateString()); // it crashes, myDate is incorrect


I get
TypeError: Method Date.prototype.toDateString called on incompatible receiver [object Object]
.

How can I override the
Date
constructor? Is it possible?

Answer

According to this question and the accepted answer, this happens because subclassing Date is not allowed in ES5. The following ES6 code works in Chrome because Chrome natively supports ES6 classes (it's exactly the same as your code, except I removed type annotations):

class MyDate extends Date {
  constructor(str) {
    super(str);
  }
}

var myDate = new MyDate("2016-10-20T12:30:00+0200");
console.log(myDate.toDateString());

If you only need this to work in environments that natively support ES6 classes, change TypeScript's --target compiler optionto 'es6'. Otherwise, you will need to do something else.

One workaround might be to define MyDate so that it has a Date as a member variable. For example:

class MyDate {

  private date:Date;

  constructor(str: string) {
    this.date = new Date(str);
  }

  toDateString(): string {
    return this.date.toDateString();
  }
}