typings / discussions

For discussions and issues with Typings or TypeScript definitions
7 stars 0 forks source link

Best practices for npm module typing? #21

Closed JoshGlazebrook closed 8 years ago

JoshGlazebrook commented 8 years ago

So I recently started using Typescript and of course I want to use my own packages with it and include the typings files inside the npm package itself.

My npm package is designed where the root entry point points to a "class" that you use new on to create a new instance of said class.

const SmartBuffer = require('smart-buffer');
let buff = new SmartBuffer();

What I struggled with was how to properly write the definitions files for it. Do I need to wrap it in a module? Just export declare a class? Eventually I got it to where I can import with typescript like this:

import SmartBuffer = require('smart-buffer');
let buff = new SmartBuffer();

And vscode/webstorm etc all have intellisense for the instance buff.

I just wanted to make sure this is the proper way to write the definition files in this particular instance:

https://github.com/JoshGlazebrook/smart-buffer

(there is only one .d.ts file so it shouldn't be too much of a pain to look through)

demurgos commented 8 years ago

Your .d.ts is matching one of the official examples (without the static methods). I looked at it and it looks fine.

I agree that a list of good practices might be useful.

Do I need to wrap it in a module? Just export declare a class?

As a rule of thumb, the question to ask is "how tsc would have exported my external module if it was written in TS". In this case I think that a simple class export is the best fit.

Now, there is one thing I can tell for sure: using module is not considered a good practice in typings. If you want to declare an namespace for interfaces, use namespace. (a module declaration can create globals which can lead to conflicts on the consumer side).

JoshGlazebrook commented 8 years ago

Awesome. Thank you.