如何为这个javascript库编写打字稿定义文件?

时间:2016-10-10 23:11:05

标签: javascript typescript definition

我需要调用以下javascript:

var jslib = jslib || (function() {
var publicMethods = {
    encrypt: function (algorithm, keyHandle, buffer) {
        // implementation
    }
};

return publicMethods;
})();

我是打字稿的新手,你能否分享一下打字稿定义对于上面的javascript和调用模式的看法?

提前致谢。

1 个答案:

答案 0 :(得分:1)

我假设以下目录结构

├── lib
│   ├── jslib.d.ts
│   └── jslib.js
├── src
    └── t.ts

jslib.js

var jslib = jslib || (function () {
  var publicMethods = {
    encript: function () {
      return
    }
  };

  return publicMethods;
})();

module.exports = jslib;

jslib.d.ts

declare namespace jslib {
  function encript(): void;
}

export = jslib;

t.ts

import jslib = require('../lib/jslib');

jslib.encript();

选中node_modules/.bin/tsc --traceResolution

======== Resolving module '../lib/jslib' from '/home/zjk/dev/webnote/ts1/src/t.ts'. ========
Explicitly specified module resolution kind: 'NodeJs'.
Loading module as file / folder, candidate module location '/home/zjk/dev/webnote/ts1/lib/jslib'.
File '/home/zjk/dev/webnote/ts1/lib/jslib.ts' does not exist.
File '/home/zjk/dev/webnote/ts1/lib/jslib.tsx' does not exist.
File '/home/zjk/dev/webnote/ts1/lib/jslib.d.ts' exist - use it as a name resolution result.
Resolving real path for '/home/zjk/dev/webnote/ts1/lib/jslib.d.ts', result '/home/zjk/dev/webnote/ts1/lib/jslib.d.ts'
======== Module name '../lib/jslib' was successfully resolved to '/home/zjk/dev/webnote/ts1/lib/jslib.d.ts'. ========

jslib.jsjslib.d.ts放在同一目录中至关重要。