如何在TypeScript中扩展Luxon DateTime类的静态方法?
为Luxon DateTime类扩展静态方法的TypeScript类型问题
我尝试给Luxon的DateTime类添加静态方法fromDob,实现代码如下:
DateTime.fromDob = function(dob: number | string | DateTime) { if (dob instanceof DateTime) { return dob } if (dob && (typeof dob === 'number' || typeof dob === 'string')) { return DateTime.fromFormat(String(dob), DOB) } return null }
但TypeScript报错:
Property 'isInFuture' does not exist on type 'typeof DateTime'.ts(2339)
我曾尝试在.d.ts文件中添加模块声明,但未解决问题,声明代码如下:
declare module 'luxon/src/datetime' { export interface DateTime { public static fromDob(dob: number | string | DateTime): DateTime | null } }
解决方法
错误根源
之前的类型声明存在三个问题:
- 静态方法属于类的构造函数类型(即
typeof DateTime),而非DateTime实例接口,直接在DateTime接口里加静态方法无效 - 模块路径错误,应该声明在
luxon模块下,而非luxon/src/datetime - TypeScript接口中不能使用
public修饰符
正确的类型声明
创建luxon.d.ts文件,写入以下内容:
import { DateTime } from 'luxon'; declare module 'luxon' { namespace DateTime { export function fromDob(dob: number | string | DateTime): DateTime | null; } }
额外注意事项
- 确保
luxon.d.ts在TypeScript的编译范围内,可通过tsconfig.json的include数组配置 - 自定义的
DOB格式常量需为string类型,符合DateTime.fromFormat的参数要求
内容的提问来源于stack exchange,提问作者Erik Seyferth
相关产品推荐
相关产品推荐

