{"id":31266,"date":"2023-03-03T07:00:00","date_gmt":"2023-03-03T15:00:00","guid":{"rendered":"https:\/\/coderpad.io\/?p=31266"},"modified":"2023-06-05T13:38:32","modified_gmt":"2023-06-05T20:38:32","slug":"how-to-get-started-with-typescript-in-node-js","status":"publish","type":"post","link":"https:\/\/coderpad.io\/blog\/development\/how-to-get-started-with-typescript-in-node-js\/","title":{"rendered":"How To Get Started With TypeScript in Node.js"},"content":{"rendered":"\n<p>TypeScript was the <a href=\"https:\/\/survey.stackoverflow.co\/2022\/#most-loved-dreaded-and-wanted-language-want\" target=\"_blank\" rel=\"noopener\">third most popular<\/a> programming language in 2022, following Rust and Python. It\u2019s widely admired by the JavaScript community and used by many companies to build <a href=\"https:\/\/coderpad.io\/blog\/development\/10-javascript-data-visualization-libs\/\">front-end<\/a> and back-end applications. Typescript&#8217;s versatility enables use with any framework or technology powered by JavaScript. This includes JavaScript back-end frameworks like Node.js, which developers use to build RESTful web services and back-end systems.&nbsp;<\/p>\n\n\n\n<p>In this post, we&#8217;ll dive deeper into TypeScript and why it can be useful for you. Then you\u2019ll learn how&nbsp; to use TypeScript in a Node.js application.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is TypeScript?<\/strong><\/h2>\n\n\n\n<p><a href=\"https:\/\/www.typescriptlang.org\/docs\/\" target=\"_blank\" rel=\"noopener\">Typescript<\/a> is an open-source programming language developed by Microsoft. It\u2019s an extended version of JavaScript that offers support for using variable types.&nbsp;<\/p>\n\n\n\n<p>JavaScript itself is a weakly typed language. That means it assigns variable types at runtime instead of compile time. In Typescript, you can leverage the type system to create and declare type interfaces for your variables.&nbsp;<\/p>\n\n\n\n<p>This kind of interface defines what type, either primitive or custom, your variable poses. Therefore we can say that TypeScript is a typed superset of JavaScript. When you compile your TypeScript code, the compiler translates it back to JavaScript. Therefore, you can also think of TypeScript as an abstraction layer for JavaScript applications, with an extended type system.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>TypeScript: pros and cons<\/strong><\/h2>\n\n\n\n<p>As a weakly typed language, <a href=\"https:\/\/coderpad.io\/blog\/development\/what-you-never-learned-about-javascript-functions\/\">JavaScript<\/a> isn&#8217;t an ideal choice for writing applications that can grow in size and complexity. This is because variable types aren&#8217;t known beforehand, and there\u2019s no development-time check to validate them. A string variable may be assigned a boolean at some point later that causes a bug in the program. <a href=\"https:\/\/en.wikipedia.org\/wiki\/TypeScript#:~:text=Types.%5B25%5D-,Design,-%5Bedit%5D\" target=\"_blank\" rel=\"noopener\">TypeScript<\/a> prevents this by identifying those kinds of errors beforehand, due to its strictly typed nature.&nbsp;<\/p>\n\n\n\n<p>TypeScript has been around for quite some time and is loved by the community. Adding support for variable types in your program not only makes it less prone to errors but also makes your code self-documenting. If any other developer looks at your TypeScript function and the variables it takes and returns, they can easily understand what&#8217;s happening in that code.&nbsp;<\/p>\n\n\n\n<p>In addition, TypeScript has enhanced IDE support that automatically recommends types for your variables, function parameters, return values, and so on. Moreover, as a superset of JavaScript, you can always go back to writing a TypeScript function in pure JavaScript, if needed.&nbsp;<\/p>\n\n\n\n<p>Therefore, TypeScript makes your application more robust, reduces errors, and makes your code self-documenting. However, as a strongly typed version of JavaScript, it has a steeper learning curve. Hence some developers find it difficult to work with, especially beginners. &nbsp;&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Getting started with TypeScript in Node.js<\/strong><\/h2>\n\n\n\n<p>Now that you have an idea about what TypeScript is, let&#8217;s see how we can set up and start using it in a Node.js application.&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Setup<\/strong><\/h3>\n\n\n\n<p>First, we&#8217;ll create a new directory for our Node.js project:&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs shcb-wrap-lines\">$ mkdir nodejs-typescript<\/code><\/span><\/pre>\n\n\n<p>Then, we&#8217;ll navigate inside this directory and create a new Node.js project:&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs shcb-wrap-lines\">$ cd nodejs-typescript &amp;&amp; npm init -y<\/code><\/span><\/pre>\n\n\n<p>The above command should return an auto-generated <code>package.json<\/code> file as shown below:&nbsp;<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/d2h1bfu6zrdxog.cloudfront.net\/wp-content\/uploads\/2023\/02\/img_63fc74b8a7e4b.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\">A boilerplate <code>packgae.json<\/code> file generated from the <code>npm init -y<\/code> command.<\/figcaption><\/figure>\n<\/div>\n\n\n<p>Great! Now, let&#8217;s install TypeScript by running the following command in the root directory of the project:&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs shcb-wrap-lines\">$ npm i typescript -save-dev<\/code><\/span><\/pre>\n\n\n<p>I also like to install the <code>@types\/node<\/code> module. This contains the type declarations for some common Node.js modules, like the file system and OS.&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs shcb-wrap-lines\">$ npm i -D @types\/node<\/code><\/span><\/pre>\n\n\n<p>You&#8217;re all set! You should now have a <code>node_modules<\/code> folder in the project, along with a <code>package.json<\/code> file.&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Adding a TypeScript config file<\/strong><\/h3>\n\n\n\n<p>Next, create a file called <code>tsconfig.json<\/code> in the root directory with the following contents:&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"JSON \/ JSON with Comments\" data-shcb-language-slug=\"json\"><span><code class=\"hljs language-json shcb-wrap-lines\">{\n\n\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-attr\">\"compilerOptions\"<\/span>: {\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-attr\">\"module\"<\/span>: <span class=\"hljs-string\">\"NodeNext\"<\/span>,\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-attr\">\"moduleResolution\"<\/span>: <span class=\"hljs-string\">\"NodeNext\"<\/span>,\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-attr\">\"target\"<\/span>: <span class=\"hljs-string\">\"ES2020\"<\/span>,\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-attr\">\"sourceMap\"<\/span>: <span class=\"hljs-literal\">true<\/span>,\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-attr\">\"outDir\"<\/span>: <span class=\"hljs-string\">\"dist\"<\/span>,\n\n\u00a0\u00a0\u00a0\u00a0},\n\n\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-attr\">\"include\"<\/span>: &#91;<span class=\"hljs-string\">\"*\"<\/span>],\n\n\u00a0\u00a0}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JSON \/ JSON with Comments<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">json<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>This file configures the behavior of the Typescript compiler. Let&#8217;s quickly go over what each compiler option means.&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>module<\/code> option defines the module system for your application.<\/li>\n\n\n\n<li>The <code>target<\/code> specifies the version of JavaScript our code will compile to.<\/li>\n\n\n\n<li>The <code>sourceMap<\/code> option, set to true, compiles JavaScript code back to TypeScript for debugging, when needed.<\/li>\n\n\n\n<li>The <code>outDir<\/code> specifies the output directory where your compiled JavaScript code will reside.<\/li>\n\n\n\n<li>The <code>include<\/code> option tells Typescript where to look for the files to build.<\/li>\n\n\n\n<li>The <code>*<\/code> indicates that all our TypeScript code will live directly in the root directory.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Building a TypeScript project<\/strong><\/h3>\n\n\n\n<p>You have everything set up now. Let&#8217;s create our first script in Typescript and build it in JavaScript. Create a new file called <code>app.ts<\/code> in the root directory. Here, you&#8217;ll add some fairly simple and straightforward code to calculate the sum of two numbers:&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"TypeScript\" data-shcb-language-slug=\"typescript\"><span><code class=\"hljs language-typescript shcb-wrap-lines\"><span class=\"hljs-keyword\">const<\/span> a: <span class=\"hljs-built_in\">number<\/span> = <span class=\"hljs-number\">10<\/span>;\n\n<span class=\"hljs-keyword\">const<\/span> b: <span class=\"hljs-built_in\">number<\/span> = <span class=\"hljs-number\">20<\/span>;\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">add<\/span>(<span class=\"hljs-params\">a: <span class=\"hljs-built_in\">number<\/span>, b: <span class=\"hljs-built_in\">number<\/span><\/span>): <span class=\"hljs-title\">number<\/span> <\/span>{\n\n\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-keyword\">return<\/span> a + b;\n\n}\n\n<span class=\"hljs-keyword\">const<\/span> sum=add(a,b);\n\n<span class=\"hljs-built_in\">console<\/span>.log(<span class=\"hljs-string\">`Sum of <span class=\"hljs-subst\">${a}<\/span> and <span class=\"hljs-subst\">${b}<\/span> is <span class=\"hljs-subst\">${sum}<\/span>`<\/span>);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">TypeScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">typescript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>All Typescript files get a <code>.ts<\/code> extension. Notice how we declared types for the variables, function parameters, and return values. You&#8217;ve written your first Typescript code in Node.js &#8212; not bad!&nbsp;<\/p>\n\n\n\n<p>Now let&#8217;s compile it. In your <code>package.json<\/code> file, under the <code>scripts<\/code> section, add the following script:&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"JSON \/ JSON with Comments\" data-shcb-language-slug=\"json\"><span><code class=\"hljs language-json shcb-wrap-lines\">{\n...\n\n\u00a0<span class=\"hljs-attr\">\"scripts\"<\/span>:{\n\n\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-attr\">\"build\"<\/span>: <span class=\"hljs-string\">\"tsc\"<\/span>,\n\n\u00a0\u00a0\u00a0\u00a0\u00a0...\n\n\u00a0\u00a0}\n\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JSON \/ JSON with Comments<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">json<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Use the following command to execute the above script:&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs shcb-wrap-lines\">$ npm run build<\/code><\/span><\/pre>\n\n\n<p>It should look through your TypeScript files in the root directory and start compiling them:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/d2h1bfu6zrdxog.cloudfront.net\/wp-content\/uploads\/2023\/02\/img_63fc74ba26cd9.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\">The TypeScript build process.<\/figcaption><\/figure>\n<\/div>\n\n\n<p>Once that finishes, you should see a <code>dist<\/code> directory with the following files:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs shcb-wrap-lines\">|- dist\n  |- app.js\n  |- app.js.map\n|- node_modules\n|- app.ts\n|- package-lock.json\n|- package.json\n|- tsconfig.json <\/code><\/span><\/pre>\n\n\n<p>Here, <code>app.js.map<\/code> represents the source map code, whereas <code>app.js<\/code><strong> <\/strong>file represents the compiled JavaScript code:&nbsp;<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/d2h1bfu6zrdxog.cloudfront.net\/wp-content\/uploads\/2023\/02\/img_63fc74ba622ef.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\">Compiled JavaScript code from TypeScript code.<\/figcaption><\/figure>\n<\/div>\n\n\n<p>You can now use this (<code>app.js<\/code>) JavaScript file in production wherever you like!&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Using ts-node<\/strong><\/h3>\n\n\n\n<p>You&#8217;ve seen how to build and compile a TypeScript project to JavaScript for production, but what about development-time or run-time? You can run your Node.js app in dev mode and see any logs it creates in the terminal. You can do the same with TypeScript. For that, we need to use a package called <code>ts-node<\/code>.&nbsp;<\/p>\n\n\n\n<p>It&#8217;s a just-in-time compiler for your TypeScript project that provides an execution engine for your TypeScript code. You can use it to run your TypeScript files locally at development time. You can either install <code>ts-node<\/code> in your project as a development dependency or install it globally:&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs shcb-wrap-lines\">$ npm i -g ts-node<\/code><\/span><\/pre>\n\n\n<p>Now you can run any Typescript file you want using the following command:&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs shcb-wrap-lines\">$ npx nodemon app.ts<\/code><\/span><\/pre>\n\n\n<p>We use <code>nodemon<\/code> here, which automatically watches for changes and runs the file again if it finds any:&nbsp;<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" src=\"https:\/\/d2h1bfu6zrdxog.cloudfront.net\/wp-content\/uploads\/2023\/02\/img_63fc7c5b0a397.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\">The nodemon process running.<\/figcaption><\/figure>\n<\/div>\n\n\n<p>As you can see, the console output prints to the terminal. If you make any further changes to the <code>app.ts<\/code> file, the watcher should automatically restart the server.&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Is it OK to use ts-node in production?<\/strong><\/h3>\n\n\n\n<p>You can use the ts-node development-time tool locally with Node.js to run your TypeScript application. You can also use it to debug your application in development mode.&nbsp;<\/p>\n\n\n\n<p>But you don&#8217;t really need to use it for production because for your production application, you don&#8217;t need a just-in-time compiler for production. The only thing you need for a production Node.js TypeScript application is the compiled JavaScript version or the <code>dist<\/code> directory that you saw earlier.<\/p>\n\n\n\n<p>However, if you still want to use <code>ts-node<\/code> in production, you can because there\u2019s no performance overhead associated with it.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>TypeScript best practices&nbsp;<\/strong><\/h2>\n\n\n\n<p>Some novice developers, as well as experienced developers, find TypeScript tricky to work with. Here are some of the best practices you can follow when working with TypeScript:&nbsp;<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Use <code>let<\/code> and <code>const<\/code> wherever possible, instead of blindly using <code>var<\/code> for variable declarations. You should use <code>let<\/code> for local variable declarations. For variables that don&#8217;t mutate, use <code>const<\/code><strong>.<\/strong><\/li>\n\n\n\n<li>To compare two variables, use <code>===<\/code> instead of <code>==<\/code> for a more fool-proof comparison that incorporates type checks in addition to the value.<\/li>\n\n\n\n<li>Avoid using the <code>any<\/code> type for your variables as much as possible. The type <code>any<\/code> exists for complex use cases where it&#8217;s difficult to assert the type of a variable at the time of definition or declaration. Oftentimes, developers use it casually. This can make your code more prone to type errors and bugs in production.<\/li>\n\n\n\n<li>Understand the difference between the <code>any<\/code> and the <code>unknown<\/code> type when you use them with your variables. You cannot use methods and properties on a variable with the type <code>unknown<\/code>. However, you can do so with a variable of type <code>any<\/code><strong>.<\/strong><\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In my opinion, TypeScript is an awesome tool for writing back-end applications in Node.js. It may initially feel difficult to get the hang of, but once you do, you&#8217;ll never want to go back to JavaScript again. It gives you confidence that your code has no type errors and also helps other developers understand your code.<\/p>\n\n\n\n<p><br><em>This post was written by Siddhant Varma. <\/em><a href=\"https:\/\/www.linkedin.com\/in\/siddhantvarma99\/\" target=\"_blank\" rel=\"noopener\"><em>Siddhant<\/em><\/a><em> is a full stack JavaScript developer with expertise in frontend engineering. He\u2019s worked with scaling multiple startups in India and has experience building products in the EdTech and healthcare industries. Siddhant has a passion for teaching and a knack for writing. He&#8217;s also taught programming to many graduates, helping them become better future developers.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>TypeScript was the third most popular programming language in 2022, following Rust and Python. It\u2019s widely admired by the JavaScript community and used by many companies to build front-end and back-end applications. In this post, let&#8217;s dive into TypeScript, learn how to get started with TypeScript in a Node.js application, and then cover ts-node.<\/p>\n","protected":false},"author":1,"featured_media":31345,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[9],"tags":[],"persona":[29],"blog-programming-language":[41],"keyword-cluster":[],"class_list":["post-31266","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-development"],"acf":[],"_links":{"self":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts\/31266","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/comments?post=31266"}],"version-history":[{"count":49,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts\/31266\/revisions"}],"predecessor-version":[{"id":31521,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts\/31266\/revisions\/31521"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/media\/31345"}],"wp:attachment":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/media?parent=31266"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/categories?post=31266"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/tags?post=31266"},{"taxonomy":"persona","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/persona?post=31266"},{"taxonomy":"blog-programming-language","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/blog-programming-language?post=31266"},{"taxonomy":"keyword-cluster","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/keyword-cluster?post=31266"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}