我学习Typescript,我试图用数组扩展创建方便的功能。下面的例子可以在Typescript中使用,但是我的编辑器会抛出TypeError:…所有其他扩展工作良好,但读取空列表,我不能以这种方式。我从StackOverflow尝试了许多解决方案,但无论如何都不起作用。有人能解释一下它是怎么工作的吗?
declare global {
interface Array<T> {
isNotEmpty(): boolean;
isEmpty(): boolean;
}
}
Array.prototype.isNotEmpty = function <T>(this: T[]): boolean {
return !!this.length;
};
Array.prototype.isEmpty = function <T>(this: T[]): boolean {
return !this.length;
};
export { };
创建一个新的声明文件,例如Array.d.ts
,其中包含您要添加的声明:
declare global {
interface Array<T> {
isNotEmpty(): boolean;
isEmpty(): boolean;
}
}
然后在你的tsconfig中的include属性下。将路径添加到.d.ts
文件中,如下所示:
"include": [
"src/*.ts", // Or wherever your source code lies
"Array.d.ts" // <- this is the new declaration
],