Overwrite function in TypeScript

允我心安 提交于 2019-12-13 07:27:14

问题


TypeScript: view on playground

alert = (function (origAlert) {
    return function (...messages: any[]) {
        origAlert(messages.join(" "))
    }
})(alert)

// Example
alert(1, 2)

I want to overwrite / redefine the function alert(message?: any) wich has already been declared in lib.d.ts before: declare function alert(message?: any): void;

But alert = function... throws "Invalid left-hand side of assignment expression."

The point is that, function alert(...messages: any[]) { /* ... */ } would work* does not even work aswell, but I need to use the original alert. And I'd dislike to define an extra const origAlert = alert before the function.

How can I do this?


Note that the compiled JavaScript in the Playground works as intended.

*on TypeScript Playground it works, but in Visual Studio it throws "Overload signatures must all be ambient or non-ambient"


回答1:


declare function alert(...messages: any[]): void;

window.alert = ((orig) => {
    return (...messages: any[]) => orig(messages.join(" "));
})(alert);

alert(1, 2)


来源:https://stackoverflow.com/questions/34238497/overwrite-function-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!