javascript - 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();
}
请帮我解决这个问题。我哪里做错了?
我真的很感谢你的帮助。
解决方案
你可以以我创建的这个扩展添加毫秒为例:
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});
};
推荐阅读
- javascript - 确保组件只能是特定父组件的子组件
- javascript - Browser 和 Pure Data 之间的 OSC 通信(两台计算机)
- php - 如何将连接表的结果数组存储在mysql的行结果中?
- java - 未设置模板变量时,我可以使用 Thymeleaf 引发可捕获的异常吗?
- mysql - 来自多个有关系的表的 2 个日期之间的 Mysql 查询
- java - 在 Java 中,我们应该在处理多个接口时使用泛型吗?
- security - 如何保护机器人框架 URL 不被直接访问
- ios - 当用户的凭据在后台更改时如何处理离线数据同步?
- javascript - 带有 mongoDB 的节点 Js Cli
- python - 如何有效地找到最小长度的峰?