原型如何在打字稿上扩展? [英] How does prototype extend on typescript?
本文介绍了原型如何在打字稿上扩展?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我扩展了函数原型但是typescript无法识别它。
i extended function prototype but typescript doesn't recognize it.
Function.prototype.proc = function() {
var args, target, v;
var __slice = [].slice;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
target = this;
while (v = args.shift()) {
target = target(v);
}
return target;
};
// generated by coffee-script
var foo: (number) => (string) => number
= (a) => (b) => a * b.length;
console.log(foo.proc("first", "second"))
结果:tsc -e
The property 'proc' does not exist on value of type 'Function'
如何扩展此对象?
推荐答案
标准typescript lib中有一个Function接口,用于声明Function对象的成员。您将需要将proc作为该接口的成员与您自己的add一起声明如下:
There is a Function interface in the standard typescript lib which declares the members of Function objects. You will need to declare proc as a member of that interface with your own add on like the following:
interface Function {
proc(...args: any[]): any;
}
此界面需要在您打算使用'proc'的任何地方引用。
This interface will need to be referenced from anywhere you intend to use 'proc'.
这篇关于原型如何在打字稿上扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文