【问题标题】:Luxon DateTime: adding type for extensionLuxon DateTime:为扩展添加类型
【发布时间】:2021-08-31 10:05:09
【问题描述】:

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

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

我已经尝试过以下方法

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

但是当我使用DateTime时会抛出'DateTime' only refers to a type, but is being used as a value here.之类的错误,例如:

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

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

非常感谢您的帮助。

【问题讨论】:

    标签: javascript typescript luxon


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-27
      • 2018-01-20
      • 1970-01-01
      • 2018-06-26
      • 2022-01-14
      相关资源
      最近更新 更多