外部声明用于内置Node类的Monkey补丁

问题描述 投票:0回答:1

我写了一个名为cached-date的NPM包,猴子修补了Date类。它缓存日期的标准字符串表示。

除了我无法让我的Typescript项目识别包中包含的类型定义外,每件事都很有效:

// index.d.ts

declare interface Date {
    toCachedString(): string;
    toCachedDateString(): string;
    toCachedISOString(): string;
    toCachedJSON(): string;
    toCachedTimeString(): string;
    toCachedUTCString(): string;
}

以下代码产生编译器错误Property 'toCachedISOString' does not exist on type 'Date'

// Typescript application

require('cached-date');
const date = new Date();
const isoStr = date.toCachedISOString();

package.json的相关部分如下:

// package.json

"main": "index.js",
"types": "index.d.ts",

奇怪的是,当我将index.d.ts移动到我的项目的本地声明文件夹("paths"中的tsconfig.json)时,一切都很好,没有变化,并称之为Date.d.ts

同样,当我在应用程序中放入以下声明时,一切都很好:

// application

export interface Date {
    toCachedString(): string;
    toCachedDateString(): string;
    toCachedISOString(): string;
    toCachedJSON(): string;
    toCachedTimeString(): string;
    toCachedUTCString(): string;
}

我是否有一种特殊的方式将声明外部合并到内置类型?谢谢!

typescript declaration typescript-typings built-in monkeypatching
1个回答
0
投票

我想到了。实际上,这有点令人尴尬。只需替换这个:

require("cached-date");

有了这个:

import "cached-date";

现在,Typescript引入了模块的声明,一切都很顺利。

有趣的是,这表明在没有声明的情况下加载模块的方法。

© www.soinside.com 2019 - 2024. All rights reserved.