在帖子中“打字稿扩展字符串静态” https://stackoverflow.com/questions/17843215/typescript-extend-string-static,我得到了一些我们可以扩展打字稿现有基类的内容,例如添加新方法
interface StringConstructor {
isNullOrEmpty(str:string):boolean;
}
String.isNullOrEmpty = (str:string) => !str;
它确实有效。但对于通用接口,我遇到了问题。例如,我需要在 Array.h 中添加新方法 contains() 。我使用以下代码:
//1
interface Array<T> {
contain(item: T): boolean;
}
//2
?????? = (item: T) => {
// ....
return true;
};
步骤1之后,在VS intellisense中确实弹出包含方法,但是我在哪里可以实现方法?
由于接口中的定义已经绑定到通用约束,因此在实现中您可以将其视为任何:
interface Array<T> {
contain(item: T): boolean;
}
Array.prototype.contain = function(item) {
return this.some(obj => item == obj);
};
另外,不要对原型方法使用箭头函数,原因如下:
interface Array<T> {
fn(): void;
}
Array.prototype.fn = () => {
console.log(this);
};
let a = [];
a.fn(); // Window
But:
Array.prototype.fn = function() {
console.log(this);
};
let a = [];
a.fn(); // []
如果你的目标是es5
或更低,那么编译器将箭头函数转换为常规函数并不重要,但如果您随后切换到目标es6
(并且箭头功能将持续存在)那么您的代码将被破坏,而您将不明白为什么。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)