Angular 7向基本体添加扩展方法
我想给原语添加几个方法。 我有以下文件: 字符串扩展名。ts:Angular 7向基本体添加扩展方法,angular,extension-methods,typescript-typings,angular7,Angular,Extension Methods,Typescript Typings,Angular7,我想给原语添加几个方法。 我有以下文件: 字符串扩展名。ts: interface String { isNullOrEmpty(this: string): boolean; } String.prototype.isNullOrEmpty = function (this: string): boolean { return !this; }; export {}; // this file needs to be a module String.prototype.is
interface String {
isNullOrEmpty(this: string): boolean;
}
String.prototype.isNullOrEmpty = function (this: string): boolean {
return !this;
};
export {}; // this file needs to be a module
String.prototype.isNullOrEmpty = function (this: string): boolean {
return !this;
};
我有一个组件,其代码如下:
constructor () {
let a = "asd";
alert(a.isNullOrEmpty());
}
顶部不添加导入。
当我运行客户端时,它在该行崩溃
a.isNullOrEmpty is not a function
当我检查代码时,我发现那里没有包含我的string-extension.ts文件。
我非常熟悉C#中的概念,但我不太熟悉TypeScript中的概念,因此如果您需要更多信息,我将提供
谢谢。首先,创建
global.d.ts.
文件以设置签名
global.d.ts.
export {}; // this file needs to be a module
declare global {
interface String {
isNullOrEmpty(this: string): boolean;
}
}
字符串扩展名。ts:
interface String {
isNullOrEmpty(this: string): boolean;
}
String.prototype.isNullOrEmpty = function (this: string): boolean {
return !this;
};
export {}; // this file needs to be a module
String.prototype.isNullOrEmpty = function (this: string): boolean {
return !this;
};
现在在main.ts中导入扩展名
import './string-extension'
src/global.d.ts(1,9):错误TS2669:全局范围的扩充只能直接嵌套在外部模块或环境模块声明中。是的。在某人的回答中也看到了这一点,并且它起了作用。谢谢你,我也认为,提及global.d.ts
文件应该放在哪里可能是明智的。如果我没弄错的话,这应该是角度投影的根,对吗?