Ori*_*ael 2 extension-methods typescript-typings angular angular7
我想为基元添加一些方法。我有以下文件:
string-extension.ts:
interface String {
isNullOrEmpty(this: string): boolean;
}
String.prototype.isNullOrEmpty = function (this: string): boolean {
return !this;
};
Run Code Online (Sandbox Code Playgroud)
我有一个包含以下代码的组件:
constructor () {
let a = "asd";
alert(a.isNullOrEmpty());
}
Run Code Online (Sandbox Code Playgroud)
没有导入被添加到顶部。当我运行客户端时,它在该行崩溃。
a.isNullOrEmpty is not a function
Run Code Online (Sandbox Code Playgroud)
当我检查代码时,我发现我的string-extension.ts文件未包含在其中。我对C#中的概念非常熟悉,但对TypeScript不太了解,因此,如果您需要更多信息,请提供。
谢谢。
首先,创建global .d.ts.文件以设置签名。
全球性
export {}; // this file needs to be a module
declare global {
interface String {
isNullOrEmpty(this: string): boolean;
}
}
Run Code Online (Sandbox Code Playgroud)
string-extension.ts:
export {}; // this file needs to be a module
String.prototype.isNullOrEmpty = function (this: string): boolean {
return !this;
};
Run Code Online (Sandbox Code Playgroud)
现在在main.ts导入扩展
import './string-extension'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
706 次 |
| 最近记录: |