我想向基元添加一些方法。 我有以下文件:
字符串扩展.ts:
interface String {
isNullOrEmpty(this: string): boolean;
}
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 中的概念,因此如果您需要更多信息,我会提供。
谢谢。
最佳答案
首先,创建全局 .d.ts.
文件来设置签名。
global.d.ts。
export {}; // this file needs to be a module
declare global {
interface String {
isNullOrEmpty(this: string): boolean;
}
}
字符串扩展.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 向原语添加扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53206823/