简体   繁体   中英

typescript module as function

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 ?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM