简体   繁体   中英

how to write typescript definition file for this javascript library?

I need call the following javascript:

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

return publicMethods;
})();

I am new to typescript, can you please share what the typescript definition will look like for the javascript above and invoke pattern?

Thanks in advance.

I'm assuming the following directory structure

├── 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();

Check with 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'. ========

It is crucial to put jslib.js and jslib.d.ts in the same directory.

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