打字稿模块作为功能

时间:2014-05-03 19:19:03

标签: node.js typescript

我正在用打字稿编写库,必须保留一些api

_(1).seconds()

问题是_是一个模块,而在之前的实现中就像那样

module.exports = valueFunction;
module.exports.seconds = seconds;

是否可以在打字稿中实现相同的内容?

1 个答案:

答案 0 :(得分:1)

这是考虑分解它并使代码完成/智能感知工作的一种方法。有一些选项可以更接近原始的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);

输出为5seconds将原始数字除以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;
}
相关问题