Luxon DateTime: adding type for extension

Viewed 609

Based on https://github.com/moment/luxon/issues/260. I would like to add extension into DateTime like bellow:

import { DateTime } from 'luxon';

function fromUnix(tsp?: number): DateTime {
  return DateTime.fromMillis(tsp * 1000);
}

function toUnix(): number {
  const seconds = (this as DateTime).toSeconds();
  return parseInt(String(seconds));
}

if (!DateTime.prototype.fromUnix) {
  DateTime.prototype.fromUnix = fromUnix;
}

if (!DateTime.prototype.toUnix) {
  DateTime.prototype.toUnix = toUnix;
}

But I don't know how to add type definition for the above methods to let typescript check it.

I'd already tried with the following

declare module 'luxon/src/datetime' {
  interface DateTime {
    fromUnix(tsp?: number): DateTime;
    toUnix():  number;
  }
}

but it will throw an error such as 'DateTime' only refers to a type, but is being used as a value here. when I using DateTime such as:

import { DateTime } from 'luxon';
class MyClass {
   start = DateTime.now();
}

Please help me clear this problem. Where did I go wrong?

I really appreciate all your help.

1 Answers

You can take this extension I created to add milliseconds as an example:

import {DateTime} from 'luxon';

declare module 'luxon/src/datetime' {
    export interface DateTime {
        plusMillis(millis: number): DateTime;
    }
}

DateTime.prototype.plusMillis = function(millis: number): DateTime {
    const _self = this as DateTime;
    return _self.plus({milliseconds: millis});
};
Related