我用打字稿写库,必须保留一些api
_(1).seconds()
事实是_是一个模块,在先前的实现中是这样的
module.exports = valueFunction;
module.exports.seconds = seconds;
有可能在打字稿中实现相同的内容吗?
这是考虑将其分解并进行代码完成/智能工作的一种方法。有一些选项更接近原始的JavaScript实现,但是,要使代码完成工作可能会有些挑战。
主函数将_
被导出,并返回一个名为的导出类Chained
。正是在这里class
,_
存在从返回值中挂起的函数。
在实现文件(sample.ts
)中:
export class Chained {
constructor(private val: number) {
}
seconds(): number {
return this.val / 1000;
}
}
export function _(val: number): Chained {
return new Chained(val);
}
然后在使用中:
/// <reference path="sample.ts" />
import sample = require('./sample');
// create a simple alias for the exported _ function:
import _ = sample._;
var val = _(5000).seconds();
console.log(val);
输出将是5
如seconds
除以原始号码1000
。
如果您需要该功能可用,例如:
_.seconds
也:
_().seconds()
当TypeScript支持Function
使用属性扩展实例时,您的选择变得更加有限,而intellisense不起作用:
// this won't work well:
export function _(val:number) : Chained {
return new Chained(val);
}
_["seconds"] = (val:number) : number => {
return val / 1000;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句