TypeScript中的覆盖功能 [英] Overwrite function in TypeScript

查看:203
本文介绍了TypeScript中的覆盖功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TypeScript:

TypeScript: view on playground

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

// Example
alert(1, 2)

我要覆盖/重新定义在lib.d.ts中已经声明过的函数alert(message?: any):declare function alert(message?: any): void;

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;

但是alert = function...会抛出" Invalid left-hand side of assignment expression. "

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

问题在于,function alert(...messages: any[]) { /* ... */ } 可以正常工作 *甚至不能正常工作,但是我需要使用原始的alert.而且我不希望在函数之前定义一个额外的const origAlert = alert.

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.

我该怎么做?

请注意,在Playground中编译的JavaScript可以按预期工作.

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

*在TypeScript Playground上可以运行,但是在Visual Studio中会抛出" Overload signatures must all be ambient or non-ambient "

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

推荐答案

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

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

alert(1, 2)

这篇关于TypeScript中的覆盖功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆