[英]typescript module as function
I'm writing the library in typescript and have to keep some api 我用打字稿写库,必须保留一些api
_(1).seconds()
the thing is that _ is a module, and in the previous implementation was like that 事实是_是一个模块,在先前的实现中是这样的
module.exports = valueFunction;
module.exports.seconds = seconds;
is it possible to implement the same in typescript ? 有可能在打字稿中实现相同的内容吗?
Here's one way to consider breaking it up, and have code-completion/intellisense work. 这是考虑将其分解并进行代码完成/智能工作的一种方法。 There are a few options that would be closer to the original JavaScript implementation, however, getting code-completion to work can be a bit challenging. 有一些选项更接近原始的JavaScript实现,但是,使代码完成工作可能会有些挑战。
The primary function _
is exported, and returns an exported class called Chained
. 主要函数_
被导出,并返回一个名为Chained
的导出类。 It's in this class
, where the functions that hang from the return value of _
would exist. 这是在这个class
,其中,从返回值挂功能_
将存在。
In the implementation file ( sample.ts
): 在实现文件( sample.ts
)中:
export class Chained {
constructor(private val: number) {
}
seconds(): number {
return this.val / 1000;
}
}
export function _(val: number): Chained {
return new Chained(val);
}
And then in use: 然后使用:
/// <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);
The output would be 5
as seconds
divides the original number by 1000
. 输出将是5
因为seconds
将原始数字除以1000
。
If you needed the function to be available like: 如果需要该功能,例如:
_.seconds
as well as: 以及:
_().seconds()
Your options become more limited as while TypeScript supports extending a Function
instance with properties, intellisense doesn't work: 当TypeScript支持使用属性扩展Function
实例时,您的选择变得更加有限,而intellisense不起作用:
// this won't work well:
export function _(val:number) : Chained {
return new Chained(val);
}
_["seconds"] = (val:number) : number => {
return val / 1000;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.