higuy
higuy

Reputation: 61

Can i extends Dayjs class?

I'm using Dayjs, typescript.

I want to use like this

export class CustomDate extends dayjs.Dayjs {
  format() {
  }
}

It returns 'TypeError: Class extends value undefined is not a constructor or null'.

When I searched this, the reason occured this problem is circular dependency, but I cannot understand it...

is it incorrect way?

Upvotes: 2

Views: 1389

Answers (1)

Olian04
Olian04

Reputation: 6872

I dug though the source for a bit, and I think this will work. However, since dayjs doesn't officially support sub-classing, I wouldn't recommend doing this.

(You might have to keep digging through the source code though: https://github.com/iamkun/dayjs/blob/4a7b7d07c885bb9338514c234dbb708e24e9863e/src/index.js)

/* Extracting the underlying Datejs class */
const Dayjs_proto = Object.getPrototypeOf(dayjs());
const Dayjs = Dayjs_proto.constructor;
Dayjs.prototype = Dayjs_proto;

class CustomDate extends Dayjs {
  constructor(date) {
    super({
      date: date,
      args: arguments,
    });
  }
  format() {
  }
}

const myCustomDateObject = new CustomDate(new Date());
console.log(myCustomDateObject);
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.10.7/dayjs.min.js"></script>

Upvotes: 1

Related Questions