Reputation:
I'm writing the library in typescript and have to keep some 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 ?
Upvotes: 0
Views: 81
Reputation: 59763
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.
The primary function _
is exported, and returns an exported class called Chained
. It's in this class
, where the functions that hang from the return value of _
would exist.
In the implementation file (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
.
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:
// this won't work well:
export function _(val:number) : Chained {
return new Chained(val);
}
_["seconds"] = (val:number) : number => {
return val / 1000;
}
Upvotes: 1