问题描述
我想为原语添加一些方法.我有以下文件:
I would like to add few methods to primitives.I have the following file:
string-extension.ts:
interface String {
isNullOrEmpty(this: string): boolean;
}
String.prototype.isNullOrEmpty = function (this: string): boolean {
return !this;
};
我有一个包含以下代码的组件:
I have a component which has the following code:
constructor () {
let a = "asd";
alert(a.isNullOrEmpty());
}
未在顶部添加任何导入.当我运行客户端时,它在该行崩溃.
no import is added at the top.When I run the client, it crashes on that line.
a.isNullOrEmpty is not a function
当我检查代码时,我发现其中没有包含我的string-extension.ts文件.我对C#中的概念非常熟悉,但对TypeScript却不太熟悉,因此,如果您需要更多信息,请提供.
When I inspect the code, i see that my string-extension.ts file wasn't included there.I am very familiar with the concept in C# but im not quite familiar with it in TypeScript, so if you need more info, ill provide.
谢谢.
推荐答案
首先,创建global .d.ts.
文件以设置签名.
first, create global .d.ts.
file to set up the signature.
global.d.ts.
export {}; // this file needs to be a module
declare global {
interface String {
isNullOrEmpty(this: string): boolean;
}
}
string-extension.ts:
export {}; // this file needs to be a module
String.prototype.isNullOrEmpty = function (this: string): boolean {
return !this;
};
现在main.ts
导入扩展名
import './string-extension'
这篇关于Angular 7向基元添加扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!