当方法被自动调用时,我正在尝试记录。(我从https://stackoverflow.com/a/5034657/11188822获得了编码)
augment(withFn) {
let name, fn;
for (name in window) {
fn = window[name];
if (typeof fn === 'function') {
window[name] = (function(n, f) { // I get an error here.
const args = arguments;
return function() {
withFn.apply(this, args);
return fn.apply(this, arguments);
};
})(name, fn);
}
}
}然后叫这个。
this.augment(function(name, fn) {
console.log('calling ' + name);
});我犯了个错误
错误在src/app/app.component.ts(81,17):ERROR TS2740: type '() => any‘类型’=>any‘中缺少以下属性: Blob、TextDecoder、TextEncoder、URL和232更多。
如何覆盖窗口函数?
发布于 2020-01-07 04:28:18
TypeScript将您的window[name]属性视为一个应该包含Blob、TextDecoder、TextEncoder等的Window接口。
原因是Window接口包含了动态属性的定义:
interface Window extends EventTarget, WindowTimers, ... {
...
[index: number]: Window;
}表示对框架中的窗口对象(window[0]、window[1]等)的引用。
您可以扩展现有的Window接口来告诉它您的情况:
declare global {
interface Window {
[index: string]: () => any; // or just any
}
}此外,您还必须显式地声明变量let name是string类型。
let name: string下面是完整的代码:
app.component.ts
export class AppComponent {
...
ngOnInit() {
this.augment(function(name, fn) {
console.log('calling ' + name);
});
}
augment(withFn) {
let name: string, fn;
for (name in window) {
fn = window[name];
if (typeof fn === 'function') {
window[name] = (function (n, f) {
const args = arguments;
return function () {
withFn.apply(this, args);
return fn.apply(this, arguments);
};
})(name, fn);
}
}
}
}
declare global {
interface Window {
[index: string]: () => any;
}
}注意:总是有更简单的方法来防止TypeScript抱怨:
抑制错误:
// @ts-ignore
window[name] = (function(n, f) {使用any关键字:
(window[name] as any) = (function(n, f) {或
(<any>window[name]) = (function (n, f) {https://stackoverflow.com/questions/59621409
复制相似问题