How to use Node.js with TypeScript

Write better Node.js applications with TypeScript

Ali Kamalizade
Published in
2 min readMay 13, 2019

--

TypeScript continues to improve and get more adaption in web development. If you are an Angular developer, then you are already used to TypeScript. Vue.js and React can also work well with TypeScript.

Advantages of TypeScript:

  • Static typing helps to catch issues early before executing your code.
  • Static typing improves code readability and can serve as documentation.
  • The syntax feels familiar to Java or C#.
  • TypeScript allows you to use the latest JavaScript features in your code which is compiled to work even in older browsers.
  • Many libraries provide built-in types or there are types in the DefinitelyTyped repository which can be easily used.
  • IDEs like IntelliJ or Visual Studio Code have great support for TypeScript.

Disadvantages of TypeScript:

  • TypeScript has a (small) learning curve.
  • Not every library (especially older ones) has typings. You can create typings yourself, though.
  • For small projects, TypeScript might be too much.

However, TypeScript can also be used in the backend. Node.js is a good choice for backend especially if you know JavaScript. The most popular choice for Node is Express, an easy-to-use web framework.

How to use TypeScript in Node (with Express)

  1. Setup an Express project if you have not already.
  2. Install TypeScript as dev-dependency: npm i typescript --save=dev.
  3. Install the following types to get the best TypeScript support in your IDE: npm i @types/node @types/express --save-dev.
  4. Rename your .js files (e.g. routes) to .ts to use TypeScript.
  5. Optional: Install ts-node-dev: npm i ts-node-dev --save-dev. This improves your development process by automatically restarting your server when you make code changes. This is similar to nodemon which works with plain JavaScript.
  6. Optional: to check whether our code compiles correctly, we should run the build on CI. A simple script in package.json which runs a TypeScript build that generates JavaScript code could like this: "build:ci": "tsc".
  7. Optional: Use Jest for unit and API testing. Testing should be an essential part of software development projects. Jest is a viable solution as it provides a great testing experience and it works well with TypeScript. Here is an article about how to use Jest with TypeScript and Node.js.

Conclusion

Thanks for reading this article about how to use Node.js with TypeScript. As you can see, it is easy to setup a Node.js project with TypeScript. Personally, I have become a big fan of TypeScript since it can be used in any web project and it improves my developer experience a lot. Let me know in the comments if you have any questions.

--

--

Co-founder of Sunhat. Posts about software engineering, startups and anything else. 有難うございます。🚀