为什么在Angular类型脚本类中使用"Function.protype.run"是非法的



我想在我的Angular组件中定义一个名为run的全局新函数,如下所示:

Function.prototype.run = function (delay: number) {
// some content;
};

但是编译器生成了一个错误,Property 'run' does not exist on type 'Function'.如果我只使用普通的java脚本执行相同的代码,并使用node.js进行编译,它编译起来没有任何问题。有人知道为什么吗?

要让tsc不打扰您,只需转换为any

(Function.prototype as any).run = function (delay: number) {
// some content;
};

或者创建一个新型

type myType = Function & { run: Function };
(Function.prototype as myType).run = function (delay: number) {
// some content;
};

您也可以使用Object类来定义新属性

Object.defineProperty(Function.prototype, 'run', {
value: (delay: number) => {},
});

通常不建议向本机JavaScript对象添加属性,但如果您真的想这样做,只需利用TypeScript的声明合并:

declare global {
interface Function {
run: (delay: number) => void;
}
}
Function.prototype.run = function (delay: number) {
// some content;
};

TypeScript游乐场

最新更新