Typescript tutorial for JavaScript developers

In parallel to Kotlin in the other project I’ve also been learning TypeScript. These two languages are very similar in most of concepts, however it is quite difficult to learn them both at the exact same time because of the different syntax. Again, I’ve made my own quick in-code introduction to this language.

Unlike Kotlin Reference which is really clear, original TypeScript handbook is more obscure and sometimes hard to understand. Firstly, they frequently don’t provide clean, readable and working examples with description, but delve into internal implementation details instead. Secondly, sometimes on first few pages of given feature description they start with some background deliberations, while the essential content you want to read starts from the middle of the article. This is why during reading this tutorial I frequently had to reach some different sources of knowledge.

The source code for this project is on GitHub. Note that this tutorial is done using Node.js and doesn’t use any browser-related code in examples.

Using JavaScript with declaration files

in l12-js.ts TypeScript file we want to include following lib.js JavaScript library:

In order to do it, you can create TypeScript declaration (.d.ts file) on the same directory level, with exactly same name as the lib you want to include (i.e. lib.d.ts):

lib

lib.d.ts

lib.js

and declare all types exposed by JavaScript library there:

Now, you can import lib.d.ts into you TypeScript file and both, types declaration as well as original JavaScript library will be included into you project.

However, sometimes you can have more JavaScript files you want to include in a single declaration file, or declaration file name doesn’t match the JavaScript library name you want to use. In my examples I’ve also included second library declaration which name (other-lib.d.ts) is different from the original JavaScript library (lib.js):

lib

other-lib.d.ts

lib.js

The content of other-lib.d.ts is exactly the same as in previous example:

To include properly lib.js library with this declaration you can create intermediate other-lib.js library:

lib

other-lib.d.ts

other-lib.js

lib.js

in which you can use standard Node.js require clause to import all necessary JavaScript files: