0

I am trying to create a class Birthdate extending Date in typescript :

class Birthday extends Date {
  public isYoungerThen(other: Date): boolean {
    return this.getTime() > other.getTime();
  }

  get isAdult(): boolean {
    const past = new Date();
    past.setFullYear(past.getFullYear() - 18)
    return this.getTime() <= past.getTime();
  }
}

But when trying to call : new Birthday('2022-08-08T16:04:25+02:00').isAdult this fails with an error : TypeError: this is not a Date object.

Can you help me figuring out what I could have done wrong ?

Thx

stemlaur
  • 2,471
  • 2
  • 14
  • 3
  • I don’t think you can inherit Date – Daniel A. White Jul 12 '23 at 10:55
  • 4
    Can you share a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example)? [Your code](https://www.typescriptlang.org/play?jsx=0&module=1#code/MYGwhgzhAEBCCWAnALgCwCZgJ7QKYA9lcA7dGAETCOgG8BYAKGmgAcBXAIxHmGnggCaAezbEA5rkQAVVCQAUQtJIBc0SkQCUqjkKEhcYYrUbNmiXMjaIjafgDoJyKfAC2uORugA+aItmIHC2c3DwBuE2gAX0YIxz4IAEF0NhBkD21dfUNjJlNgIWIIZFZIYoBeaGJcAHc1KncNcNzmFlK7CAsAMRSQAQNEOVaiwORukF7+j2gAWmgARgAODQizCysbVHtHYIboAB4KoeQRnbCI6IYLxnzCvVw7ECExOSrahBQMbDkAcgAmAAZfr9pv8FiCFlI5gA2ZT-AAsyl+AFYANSA2H-b4aOz8JIpZCNIA) seems to run just fine. – Cuzy Jul 12 '23 at 11:00
  • You can try something like `constructor(dateString: string) { super(dateString); } ` – Luboš Hájek Jul 12 '23 at 11:19
  • I just pasted the snippet (& deleted types) in the console and it works. But you may have some issues with binding "this" to class methods... https://stackoverflow.com/questions/37973290/javascript-bind-method-does-not-work-on-getter-property – Tamás Katona Jul 12 '23 at 13:07

0 Answers0