Search code examples
javascripttypescriptarchitectureopen-sourcedefinitelytyped

How to write typescript definition files for new library?


If you were to write your own open source typescript library how would you structure the typescript and the typescript definitions? From what I understand the definition files are really there for the compiler so that when your library gets consumed there is intellisense to help the consumer.

However, how do definition files work internally when developing a library? Would you put all of your types (interfaces, classes, etc) in a {module}.d.ts file and reference the definition file internally so that you don't have to write the types twice (once in the {module}.ts and once in the {module}.d.ts?

In the typescript compiler options what is the point of setting "declaration" to true? To me it doesn't seem helpful to automate the definition file creation if it won't be very helpful (i.e. comments).

If your library has multiple modules would you write a separate definitions for each module and add references between definitions then concatenate them with some automater (i.e. gulp, grunt)?

What is the recommended way to expose your library so that both typescript consumers and javascript consumers can use your library?

How would you write tests in typescript? Would you import the typescript modules in your test files?


Solution

  • When developing your library in typescript you do not use definitions of your own classes. They are 'self contained' and already provide all type information to transpiler/IDE. The definitions are as you have mentioned for external consumers.

    The point of setting declaration to true is to get rid of tedious job of collecting type information from typescript classes and pasting it in definition files. As I have said this information is already present in typescript files and can be automatically extracted by transpiler.

    Regarding the way of how to organize your definitions and expose them - I am sure there are multiple different ways, one thing for sure - you do not want to write the same class definitions manually in two places. Having said that I can give you a sample of how I expose library project and consume it in another one. Pay attention to index.ts files there and how the root one is exposed in package.json -> typings field. There you will also find exampls of unit tests for the library via jasmine.

    Hope this will give you some information of how to go process with your library development.