我编写了一个名为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;
}
我是否有一种特殊的方式将声明外部合并到内置类型?谢谢!
答案 0 :(得分:0)
我明白了。实际上,这有点令人尴尬。只需替换它:
require("cached-date");
用这个:
import "cached-date";
现在,Typescript引入了模块的声明,一切都很顺利。
有趣的是,这表明了一种在没有声明的情况下加载模块的方法。