首页 > 解决方案 > Luxon DateTime:为扩展添加类型

问题描述

基于https://github.com/moment/luxon/issues/260。我想在DateTime中添加扩展,如下所示:

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;
}

但我不知道如何为上述方法添加类型定义以让打字稿检查它。

我已经尝试过以下

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

但它会抛出一个错误,例如'DateTime' only refers to a type, but is being used as a value here.当我使用时DateTime

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

请帮我解决这个问题。我哪里做错了?

我真的很感谢你的帮助。

标签: javascripttypescriptluxon

解决方案


你可以以我创建的这个扩展添加毫秒为例:

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});
};

推荐阅读