假设我想将以下原型添加到String类中.
String.prototype.beginsWith = function (string) {
return(this.indexOf(string) === 0);
};
Run Code Online (Sandbox Code Playgroud)
我需要添加beginWith到lib.d.ts否则它将不会complile:
declare var String: {
new (value?: any): String;
(value?: any): string;
prototype: String;
fromCharCode(...codes: number[]): string;
//Here
}
Run Code Online (Sandbox Code Playgroud)
文件被锁定,我无法编辑它.
我发布我可以var String: any在通话前声明 ,但我可以将其内置吗?
您不需要修改lib.d.ts而是首先扩展String接口,然后将新方法包含到您希望扩展的对象的原型链中.
例如
interface String {
beginsWith(text: string): bool;
}
Run Code Online (Sandbox Code Playgroud)
然后实现新功能并将其添加到原型链中
String.prototype.beginsWith = function (text) {
return this.indexOf(text) === 0;
}
Run Code Online (Sandbox Code Playgroud)
现在,您将在调用代码中获得intellisense并按预期工作.
| 归档时间: |
|
| 查看次数: |
1091 次 |
| 最近记录: |