<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tomas Nilsson on Medium]]></title>
        <description><![CDATA[Stories by Tomas Nilsson on Medium]]></description>
        <link>https://medium.com/@tomasnilsson71?source=rss-fffaf8ff7bac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MkPjsC7Bk7Nlf3yZ</url>
            <title>Stories by Tomas Nilsson on Medium</title>
            <link>https://medium.com/@tomasnilsson71?source=rss-fffaf8ff7bac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 06:01:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tomasnilsson71/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[10 vscode plugins to increase productivity]]></title>
            <link>https://tomasnilsson71.medium.com/10-vscode-plugins-to-increase-productivity-d50aacae44f3?source=rss-fffaf8ff7bac------2</link>
            <guid isPermaLink="false">https://medium.com/p/d50aacae44f3</guid>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tomas Nilsson]]></dc:creator>
            <pubDate>Sat, 19 Feb 2022 19:46:37 GMT</pubDate>
            <atom:updated>2022-02-19T19:46:37.675Z</atom:updated>
            <content:encoded><![CDATA[<p>There are so many incredible good plugins available for vscode. This article will cover super cool plugins such as such as “ErrorLens”, “Partial Diff” and “Shortcut menu”. These may significantly help you to be a more productive developer. 😁</p><h3>Error Lens</h3><p>If you just can cope with all the errors/squiggly lines in your code, then this is <em>the </em>plugin for improving on developement speed. <a href="https://marketplace.visualstudio.com/items?itemName=usernamehw.errorlens">Error Lens</a> will automatically display all errors inline together with your code. It can be configured to do so while typing, or on saving.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FBkYcvkOOlMV-SckF2z8Q.gif" /></figure><p>There are a number of settings that’s relevant to get an optimal experience. Either edit in settings or use this in settings.json , below are some pretty agressive settings (as shown in the animation above).</p><pre>{<br>     &quot;errorLens.statusBarMessageTemplate&quot;: &quot;$severity $message [$source]&quot;,<br>    &quot;errorLens.messageTemplate&quot;: &quot;:: $message ($source)&quot;,<br>    &quot;errorLens.gutterIconsEnabled&quot;: true,<br>    &quot;errorLens.delay&quot;: 0,<br>    &quot;errorLens.onSave&quot;: false,<br>    &quot;errorLens.enabledDiagnosticLevels&quot;: [<br>        &quot;info&quot;,<br>        &quot;hint&quot;,<br>        &quot;error&quot;,<br>        &quot;warning&quot;,<br>    ],<br>}</pre><h3>MarkDownLint</h3><p>If you write Markdown it’s nice to have a Linter to help out, making sure the produced Markdown follow some good practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*q593R2Uu3ZqxdGgL-pHH8A.png" /></figure><p><a href="https://marketplace.visualstudio.com/items?itemName=DavidAnson.vscode-markdownlint">MarkDownlint</a> is somewhat agressively configured per default, but it’s possible to disable warnings in settings.json .</p><pre>{<br>    &quot;markdownlint.run&quot;: &quot;onSave&quot;,<br>    &quot;markdownlint.config&quot;: {<br>        &quot;MD004&quot;: false,<br>        &quot;MD010&quot;: false,<br>        &quot;MD012&quot;: false,   // Multiple blank lines<br>        &quot;MD024&quot;: false,<br>        &quot;MD025&quot;: false,<br>        &quot;MD026&quot;: false,<br>        &quot;MD045&quot;: false,<br>    },<br>}</pre><h3>Partial Diff</h3><p><a href="https://marketplace.visualstudio.com/items?itemName=ryu1kn.partial-diff">Partial Diff</a> this is one of my favorites. It enables to diff by selecting source text and “compare text”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*YZxtPjaqEZOKfqvEl1fmhA.png" /></figure><p>The result is visualized by the vscode diff view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W8XopDqcRbCtpsk7PWLpoQ.gif" /></figure><h3>Paste JSON as code</h3><p>With the plugin <a href="https://marketplace.visualstudio.com/items?itemName=quicktype.quicktype">Paste JSON as code</a> it’s possible to take any JSON (that actually is JSON, with quotes and all) and paste it as a TypeScript (and many other languages). Install and to start it, use the command palette and choose the “Paste JSON as Code”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*8XhLzK7OQvuN4TD7_LMB2g.png" /></figure><p>The plugin tries to assess the data and make smart adjustments. Example:</p><pre>[<br>    { &quot;Name&quot;: &quot;Apple&quot;, &quot;Count&quot;: 1 },<br>    { &quot;Name&quot;: &quot;Banana&quot;, &quot;Count&quot;: 54 },<br>    { &quot;Name&quot;: &quot;Orange&quot;, &quot;Count&quot;: 19 }<br>]</pre><p>will become:</p><pre>export interface Fruit {<br>    Name:  string;<br>    Count: number;<br>}</pre><p>Important: The data in the clipboard has to be conformant JSON. Use online tools such as <a href="https://jsonlint.com/">https://jsonlint.com/</a> to verify.</p><p>As an example, this not conformant (note the trailing comma at the last line).</p><pre>[<br>    { &quot;Name&quot;: &quot;Apple&quot;, &quot;Count&quot;: 1 },<br>    { &quot;Name&quot;: &quot;Banana&quot;, &quot;Count&quot;: 54 },<br>    { &quot;Name&quot;: &quot;Orange&quot;, &quot;Count&quot;: 19 }<strong>,</strong><br>]</pre><p>Ps. Another tip is to, in debugging, to copy the object you want to convert to the clipboard. It can be done by running copy(JSON.stringify(myVariable1))</p><h3>JS/TS Import/Export sorter</h3><p>The <a href="https://marketplace.visualstudio.com/items?itemName=dozerg.tsimportsorter">JS/TS Import/Export Sorter</a> is yes another import sorter. This one is good becuase of the settings. It takes quite some time to activate after install, so please be patient (you might need to restart vscode).</p><p>These are some example settings that can be stored in settings.json .</p><pre>{<br>&quot;importSorter.generalConfiguration.exclude&quot;: [],<br>&quot;importSorter.generalConfiguration.sortOnBeforeSave&quot;: true,<br>&quot;importSorter.importStringConfiguration.maximumNumberOfImportExpressionsPerLine.count&quot;: 500,<br>&quot;importSorter.importStringConfiguration.maximumNumberOfImportExpressionsPerLine.type&quot;: &quot;maxLineLength&quot;,<br>&quot;importSorter.importStringConfiguration.quoteMark&quot;: &quot;double&quot;,<br>&quot;importSorter.sortConfiguration.customOrderingRules.defaultNumberOfEmptyLinesAfterGroup&quot;: 1,<br>&quot;importSorter.importStringConfiguration.numberOfEmptyLinesAfterAllImports&quot;: 2,<br>&quot;importSorter.sortConfiguration.joinImportPaths&quot;: true,<br>&quot;importSorter.sortConfiguration.removeUnusedImports&quot;: false,<br>}</pre><h3>React Preview</h3><p><a href="https://marketplace.visualstudio.com/items?itemName=zenclabs.reactpreview">React Preview</a> will show the result of your component while you type (Hot module reloading all of a sudden seems slow). This plugin is still in Preview with a set of bugs, but it has some serious potential. It can be good to know that most problems are resolved by restarting vscode (entirely, reloading the window doesn’t cut it).</p><p>Install it and there will appear a shortcut above your component. Click it and allow “React Preview” to scan your solution. Once it’s done, select the component you want to view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*8JuJJhXSMrRtUdLulGgmpQ.png" /></figure><p>As shown here, the feedback is <em>instant — </em>it will render the component as you type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPCX1mtfc3kyx_Kl_GXhNQ.gif" /></figure><h4>How to handle HOC components / Global css</h4><p>If there are HOCs in the system that’s used by components (such as a Router), then create a folder in the project root named __reactpreview__ and store the file Wrapper.tsx inside it. It’s also a great place to include global css files.</p><p>Here’s example:</p><pre>// Include global css<br>import &quot;../src/app.css&quot;;</pre><pre>import React from &quot;react&quot;;<br>import { BrowserRouter } from &quot;react-router-dom&quot;;</pre><pre>export const Wrapper: React.FC = ({<br>    children,<br>}) =&gt; {<br>    return &lt;&gt;<br>        &lt;BrowserRouter&gt;<br>            {children}<br>        &lt;/BrowserRouter&gt;<br>    &lt;/&gt;;<br>};</pre><p>If the plugin fails with error “error: No loader is configured for “.html” files: public/index.html” if there are a # somewhere in the parent path of the project.</p><h3>Rest Client</h3><p><a href="https://marketplace.visualstudio.com/items?itemName=humao.rest-client">Rest Client</a> is a mini Postman right inside of VSCode. Install it, create a file named request.http and post. An alternative, more advanced, plugin is <a href="https://marketplace.visualstudio.com/items?itemName=rangav.vscode-thunder-client">Thunder Client</a>.</p><p>When copying this, make sure there’s a blank line between the headers and the payload.</p><pre>PUT <a href="https://jsonplaceholder.typicode.com/posts/1">https://jsonplaceholder.typicode.com/posts/1</a> HTTP/1.1<br>content-type: application/json; charset=UTF-8</pre><pre>{<br>  &quot;id&quot;: 101,<br>  &quot;title&quot;: &quot;foo&quot;,<br>  &quot;body&quot;: &quot;bar&quot;,<br>  &quot;userId&quot;: 1<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*U9HOZRqsuOezb0fXKe9n7g.png" /></figure><h3>Shortcut Menu Bar</h3><p>The <a href="https://marketplace.visualstudio.com/items?itemName=jerrygoyal.shortcut-menu-bar">Shortcut Menu Bar</a> is extremely useful. It adds buttons for common operations for the file that’s currently opened. One of the faviourites is “Compare with saved” (compares the unsaved version with the saved one) and “Open changes with previous version” (git).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*nLYy-yrxSzGo16xwwxbCtg.png" /></figure><p>settings.json may contain settings such as:</p><pre>{<br><strong>    &quot;ShortcutMenuBar.compareWithSaved&quot;: true,<br></strong>    &quot;ShortcutMenuBar.commentLine&quot;: true,<br>    &quot;ShortcutMenuBar.beautify&quot;: false,<br>    &quot;ShortcutMenuBar.toggleWordWrap&quot;: false,<br>    &quot;ShortcutMenuBar.outdentLines&quot;: false,<br>    &quot;ShortcutMenuBar.toggleTerminal&quot;: false,<br>    &quot;ShortcutMenuBar.navigateForward&quot;: false,<br>    &quot;ShortcutMenuBar.navigateBack&quot;: false,<br>    &quot;ShortcutMenuBar.openFilesList&quot;: false<br>}</pre><h3>LintLens</h3><p>Since you’re obviosuly already using Eslint :), this plugin will help out with the .eslintrtc.json . <a href="https://marketplace.visualstudio.com/items?itemName=ghmcadams.lintlens">LintLens </a>will add descriptions to the rules and it’s very helpful :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*zzxnPsRkODktNkKWFz-3AA.png" /></figure><h3>Open</h3><p><a href="https://marketplace.visualstudio.com/items?itemName=sandcastle.vscode-open">Open</a> does something as simple as enabling right click and “Open with default application”. It’s great if you have files such as Excel or other in your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*lRGXd7hsGKTeLcT5CGdj6g.png" /></figure><h3>Others</h3><p>Here are some of the other fameous ones that I didn’t mention (because they’ve been mentioned in so many other articles).</p><ul><li><a href="https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint">Esllint</a></li><li><a href="https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens">GitLens</a></li><li><a href="https://marketplace.visualstudio.com/items?itemName=wix.vscode-import-cost">Import Cost</a></li></ul><h3>Enjoy :)</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d50aacae44f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monorepo Setup with NPM and TypeScript]]></title>
            <link>https://javascript.plainenglish.io/monorepo-setup-with-npm-and-typescript-90b329ba7275?source=rss-fffaf8ff7bac------2</link>
            <guid isPermaLink="false">https://medium.com/p/90b329ba7275</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[monorepo]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tomas Nilsson]]></dc:creator>
            <pubDate>Fri, 21 Jan 2022 14:47:01 GMT</pubDate>
            <atom:updated>2022-09-08T17:34:32.666Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*20feF-xGXfolSSne" /><figcaption>Photo by <a href="https://unsplash.com/@codestorm?utm_source=medium&amp;utm_medium=referral">Safar Safarov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Did you ever want to create one project, but with local packages? To be able to import local packages from other local packages? And the best part, to have a single node_modules directory? To have a <em>single</em> tsc to rebuild changed packages (but keep the others as-is)? And as a nice bonus, decrease both transpile and the time to start the program?</p><blockquote>The solution is to use a monorepo! This guide shows the step by step to manully setup a monorepo with NPM + TypeScript.</blockquote><h3>Goals</h3><ul><li>There will be just one node_modules folder (in the root of the monorepo).</li><li>Each piece (read: local package) of the product will have its own folder with its own package.json , tsconfig.json but use the monorepo’s node_modules.</li><li>Running tsc in the monorepo root transpiles all packages in order.</li><li>Using import .. from can reference local packages without errors.</li></ul><p><strong>Not covered by this guide:</strong> Building production builds — this guide is focused on the developer experience :)</p><h3>TL;DR; — Demo repo?</h3><p>Yes, there’s a demo <a href="https://github.com/tomnil/monorepoplate">repo</a>.</p><h3>Monorepo basics</h3><p>The monorepo consists of two pieces.</p><ul><li>The monorepo itself (the root folder with it’s configuration files, like package.json, node_modules, tsconfig.json and other)</li><li>One folder per local package, located in the packages folder. Each local package has it’s own configuration, such as package.json, tsconfig.json and src-folder and other (but <strong>no </strong><strong>node_modules</strong>).</li><li>I recommend to set up a tsconfig.package.json in the root of the monorepo, and reference that.</li></ul><p>.. and the tools of course, npm and tsc 🙂</p><h4>Package? Local packages?</h4><p>It’s a side note, but “packages” as used for a developer usually refers to packages downloaded from the internet by npm or yarn. This guide refers both to remote packages (located on the internet and probably developed by someone else than you) and <strong>local packages.</strong></p><h3>Core monorepo setup</h3><p>Let’s create the most basic folders. This demo project will be named “SuzieQ”.</p><pre># Create new empty folder</pre><pre>mkdir monorepodemo<br>cd monorepodemo</pre><pre># Create subdirectories<br>mkdir src</pre><h4>./package.json</h4><p>Next, create a ./package.json with the following content:</p><pre>{<br>  &quot;name&quot;: &quot;suzieq&quot;,<br>  &quot;private&quot;: true,<br>  &quot;scripts&quot;: {<br>    &quot;compile&quot;: &quot;tsc -b -w -i&quot;,<br>    &quot;eslint&quot;: &quot;eslint src/**/**.{ts,tsx}&quot;,<br>    &quot;eslint:fix&quot;: &quot;eslint src/**/**.{ts,tsx} --fix&quot;<br>  },<br>  &quot;devDependencies&quot;: {},<br><strong>  &quot;workspaces&quot;: [<br>    &quot;packages/*&quot;<br>  ]</strong><br>}</pre><p>⚠️Make sure the section “workspaces” is present, npm is dependent on this.</p><h4>Add core dependencies</h4><p>A great place to add core dependencies is here. This also creates the single node_modules directory needed in the entire monorepo.</p><pre>npm install <a href="http://twitter.com/types/node">@types/node</a> --save-dev<br>npm install typescript<br>npm install ts-node --save-dev</pre><h4>./tsconfig.json</h4><p>Next, create a ./tsconfig.json with the following content.</p><p>⚠️️ composite must be set to true and files must be set to an array (see <a href="https://www.typescriptlang.org/docs/handbook/project-references.html#overall-structure">https://www.typescriptlang.org/docs/handbook/project-references.html#overall-structure</a>)</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;incremental&quot;: true,<br>    &quot;target&quot;: &quot;es2019&quot;,<br>    &quot;module&quot;: &quot;commonjs&quot;,<br> <strong>   &quot;declaration&quot;: true,</strong><br>    &quot;sourceMap&quot;: true,<br>    &quot;strict&quot;: true,<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;forceConsistentCasingInFileNames&quot;: true,<br>   <strong> &quot;rootDir&quot;: &quot;./src&quot;,<br>    &quot;outDir&quot;: &quot;./superbin&quot;</strong><br>  },<br><strong>  &quot;files&quot;: [<br>    &quot;./src/index.ts&quot;<br>  ]</strong><br>}</pre><h4>./src/index.ts</h4><p>Create the ./src/index.ts file:</p><pre>console.log(&quot;This is index.ts&quot;); </pre><p>… and test it works:</p><pre># Build, this will create the &quot;superbin&quot; folder<br>tsc -b  </pre><pre># Run index.ts<br>node -r ts-node/register/transpile-only src/index.ts</pre><h4>Prepare packages folder</h4><p>The next step would be to create the packages folder, where all local packages will be placed:</p><pre>mkdir packages  # This folder should be found directly under &quot;./&quot;<br>cd packages </pre><p>So a short reminder:</p><ul><li>Each package will be placed in a subfolder inside the folder /packages.</li><li>The monorepo config will be stored in the root (i.e &quot;./&quot;)</li></ul><h3>Add a local package</h3><p>This guide shows how to manually create all files needed for a package. It’s also possible to use npm, see below. This section can be repeated as many times as necessary.</p><p>The package we will be creating is named ValidatorHelper (just to pick anything).</p><pre><em># create package folder inside of &quot;packages&quot;<br></em>mkdir ValidatorHelper<br>cd ValidatorHelper</pre><h4>./packages/ValidatorHelper/package.json</h4><p>Inside of the newly created folder, create a package.json as (this means you will now have two package.json, one in the monorepo root and one here):</p><pre>{<br>  &quot;name&quot;: &quot;@suzieq/validatorhelper&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;bin/index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;compile&quot;: &quot;tsc -b&quot;,<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;<br>}</pre><p>⚠️ Change the name and <strong>make sure</strong> <strong>the name is unique</strong> (and it must not interfere with npm downloadable packages). It’s recommended to choose a scope name, such as “@suzieq” (and it will keep your monorepos node_modules directory cleaner, read more below).</p><p>⚠️ Do not use <em>same </em>“scope name” and “project directory name”. npm will “optimizations” in node_modules where it removes the scope name from the directory name🙄</p><p>If you prefer to decrease control, basically the same result can be achieved through:</p><pre>cd /   # Go to root of monorepo<br>npm init --scope=@suzieq -w ./packages/ValidatorHelper</pre><h4>The “hack” of node_modules</h4><p>Now, this is super important. npm will automatically process any package.json found under “packages” and create a link between node_modules to this folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*YbXDCkZMiI1TMvh6UaoWGQ.png" /><figcaption>inside node_modules</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*KO2rrkKf5PUMa_5U3Bl90w.png" /><figcaption>link to the packages\validatorhelper folder</figcaption></figure><p>So after <strong>each time,</strong> a local package has been created (or really, a package.json has been created/modified) then go to the monorepo root and run npm install (and optionally check node_modules for the updated link).</p><p>⚠️ Do <em>not</em> run npm install in the package directory. node_modules is from now on “owned” by the monorepo and should exist at the root of the monorepo. More on this topic below.</p><h4>./packages/ValidatorHelper/tsconfig.json</h4><p>Now there are many examples where this file extends an already existing tsconfig.json . This works just fine, but for the sake of simplicity, that feature isn’t used here.</p><p>rootDir , outDir and composite settings must be specified.</p><p>This configuration will make the package build its result to ./bin with included TypeScript definitions.</p><pre>{<br>    &quot;compilerOptions&quot;: {<br>        &quot;incremental&quot;: true,<br>        &quot;target&quot;: &quot;es2019&quot;,<br>        &quot;module&quot;: &quot;commonjs&quot;,<br>        &quot;declaration&quot;: true,<br>        &quot;sourceMap&quot;: true,<br>        &quot;strict&quot;: true,<br>        &quot;moduleResolution&quot;: &quot;node&quot;,<br>        &quot;esModuleInterop&quot;: true,<br>        &quot;skipLibCheck&quot;: true,<br>        &quot;forceConsistentCasingInFileNames&quot;: true,<br><strong>        &quot;rootDir&quot;: &quot;./src&quot;,<br>        &quot;outDir&quot;: &quot;./bin&quot;,<br>        &quot;composite&quot;: true</strong><br>    },<br>}</pre><h4>./packages/ValidatorHelper/src/index.ts</h4><p>Finally, create the folder src and the index.ts file.</p><pre>console.log(&quot;Debug: Loading ValidateHelper/index&quot;);</pre><pre>export function ValidateUserName(name: string): boolean {<br>    return (name !== undefined &amp;&amp; name.length &gt; 10);<br>}</pre><h4>Verify package is ok</h4><p>At this point, it’s possible to check that everything seems OK.</p><pre># Change working directory<br>cd /packages/ValidatorHelper</pre><pre># Examine the combined tsconfig-file (this and the root one)<br>tsc --showconfig</pre><pre># Testrun the module (as-is)<br>node -r ts-node/register src/index.ts</pre><p>Running tsc here should transpile without errors, and produce a bin folder containing two files: index.js and types.d.ts .</p><p>It’s the same files that will be produced if tsc is run at the monorepo root.</p><pre># Just check tsc succeeds without creating &quot;bin&quot; folder:<br>tsc --noEmit</pre><pre># Build (choose the one you prefer)<br>tsc -b --listEmittedFiles --diagnostics<br>tsc -b -v </pre><pre># Test run<br>node bin\index.js</pre><h3>Repeat :)</h3><p>Add some more local packages of any type before moving on to the next section.</p><h3>Using tsc to transpile all modified packages (in a specific order)</h3><p>Now, this is where it gets interesting 😁 By issuing tsc at the top level, it can run through <em>all</em> modified packages and build them. This is especially efficient when running tsc in watch mode. But in order to do that, tsconfig.json needs to be modified to list the package(s).</p><p>Open the monorepo root ./tsconfig.jsonand add the references section as shown below.</p><p>⚠️ tsc will build in the order listed, so this means you have to have some knowledge around dependencies between packages.</p><p>️️⚠️If the filesconfiguration is missing (or badly set), then your typescript files can be built <strong>twice 😟 </strong>resulting in “junk” files in your packages src-folders. A good start to troubleshoot this is to set files to [] .</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>      // leave as-is<br>  },<br>  <strong>&quot;references&quot;: [<br>    {<br>      &quot;path&quot;: &quot;./packages/ValidatorHelper&quot;<br>    }<br>  ],<br>  &quot;files&quot;: [<br>    &quot;./src/index.ts&quot;<br>  ]<br></strong>}</pre><p>Try it:</p><pre># Transpiles packages in the order listed *and*<br># then build the files referenced by &quot;paths&quot;</pre><pre>cd /  # Go to root of monorepo<br>tsc -b -v</pre><h4>At this point…</h4><p>At this point each local package will have:</p><ul><li>been built producing a ./packages/&lt;packagename&gt;/bin -folder</li><li>exist as a link from node_modules/@scopename/&lt;packagename&gt; to ./packages/&lt;packagename&gt;</li></ul><h3>NPM Packages: Add reference between local packages</h3><p>We can use a loophole in the module resolution in TypeScript/JavaScript works. 😁If you prefer to do this “the real way”, read the next section.</p><p>Now, all our local packages are immediately available without any changes to any files (want to know more about this? Read this <a href="https://www.typescriptlang.org/docs/handbook/module-resolution.html">link</a>). Just open ./src/index.ts and add this, and you’re good to go.</p><pre>import ValidatorHelper from &#39;@suzieq/validatorhelper&#39;</pre><h4>Adding better references</h4><p>Open a package.json and add a reference to a local (already existing) package with the following.</p><pre>&quot;dependencies&quot;: {<br>    &quot;<a href="http://twitter.com/suzieq/products">@suzieq/products</a>&quot;: &quot;*&quot;<br>}</pre><p>The * means that we allow for any version.</p><h4>Avoid file references?</h4><p>So npm recommends to use file references:</p><pre>npm install .\packages\&lt;packagename&gt; -w packages\&lt;packagename&gt;</pre><p>This command will give something like this in the package.json and it doesn’t really give any advantages.</p><pre>&quot;dependencies&quot;: {<br>        &quot;<a href="http://twitter.com/suzieq/products">@suzieq/products</a>&quot;: &quot;file:packages/Products&quot;<br>}</pre><h3>NPM Packages: Add an external npm package to a local package</h3><p>Now, this is important, because this is different compared to how it’s usually done. To add an external npm package to a local npm package, the following procedure must be followed:</p><p>Go to the root of the monorepo and run npm to install a package <strong>in workspace</strong> by passing the -w parameter. The parameter accepts either the name of the package (in this case, @suzieq/validatorhelper) or the path (./packages/ValidatorHelper )</p><pre># Go to the root of the monorepo<br>cd /</pre><pre># Add axios to ValidatorHelper<br>npm install axios -w @suzieq/validatorhelper</pre><pre># Or use the path<br>npm install axios -w .\packages\ValidatorHelper</pre><p>This will install axios in the monorepos node_modules , and modify the ./packages/ValidatorHelper/packages.json . Verify the success by checking that only a single node_modules folder exists at the monorepo root.</p><p>⚠️ So to be super clear, <strong>do not do this </strong>(and if you manage to do it, see troubleshooting below for a fix):</p><pre>cd packages\ValidatorHelper<br>npm install axios</pre><h4>References in the right place?</h4><p>Does it really matter the reference to a download package is stored in the monorepo package.json vs. having it packages\packagename\package.json ? No, it will work anyway.</p><h3>Start test for one specific or all packages</h3><p>To start a npm command for all packages, just add -ws :</p><pre># Run tests for a specific package from root<br>npm test -w @suzieq/validatorhelper</pre><pre># Run tests for all local packages<br>npm test -ws</pre><h3>Start tsc for one specific or all packages</h3><pre># Build a specific package from root<br>cd /<br>tsc -b packages\ValidatorHelper</pre><pre># Build all<br>cd /<br>tsc -b -v -w -i</pre><h3>Troubleshooting</h3><h4>Repairing…</h4><p>If you’ve ended up in a position where nothing seems to help, repair the setup by doing these steps:</p><ul><li>delete the links found in node_modules\@scopename\ (deleting the entire node_modules isn’t needed). run npm install to recreate them.</li><li>delete any bin or out folders found in the entire system</li><li>verify that all the packages package.json :s are ok</li><li>stop all running tsc :s, delete <em>all</em> tsconfig.tsbuildinfo file and restart tsc <em>without the incremental flag</em></li></ul><h4>VSCode and/or TypeScript doesn’t detect/see the local package?</h4><p>Restart vscode :) Also, make sure the outDir setting tsconfig.json matches the main setting in package.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*nhl_hBOcpB9e-bLTcoRxHA.png" /><figcaption>tsconfig.json</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*sR-_30JzDFpJDEVnMSZDoA.png" /><figcaption>package.json</figcaption></figure><h4>node_modules</h4><p>Q: I’ve run npm install packagename inside a local package, and (in error) created packages\packagename\node_modules .</p><p>A: Just delete the node_modules folder and retry to install the package from the monorepo root.</p><h4>No workspaces found</h4><p>Q: I cannot run npm install axios --workspace=@xyz/abc</p><p><strong>Solution 1: <br></strong>This section is missing in the monorepo package.json :</p><pre>  &quot;workspaces&quot;: [<br>    &quot;packages/*&quot;<br>  ]</pre><p><strong>Solution 2:</strong> <br>Have you actually spelled the name correctly? :)</p><p>a) If you’ve chosen to use the path to the package, make sure it exists. Eg test dir ./thepath</p><p>b) If you’ve chosen to use the <em>name </em>of the package (as stated in the packages package.json), make sure you copy it perfectly (including the slash).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*4qw-u8YgO6KEmoPnDB_WAw.png" /></figure><p>c) Are the outDir setting tsconfig.json matching the main setting in package.json ?</p><h4>EDUPLICATEWORKSPACE</h4><p>Q: Trying to work with NPM i get EDUPLICATEWORKSPACE</p><p>A: The value of the name field is used more than once in one of the package.json :s found in one of the subdirectories of packages. NPM will list the conflicting files, just make sure all local packages has unique names.</p><h4>npm WARN workspaces abc/xyz filter set, but no workspace folder present</h4><p>Q: I cannot run npm install axios --workspace=@suzieq/apple</p><p>A: So the workspace setup seems OK, but the submitted name of the workspace isn’t found. Make sure the name parameter of --workspace can be found in a package.json :s name field:</p><pre>&quot;name&quot;: &quot;@suzieq/xyz&quot;</pre><h4>Cannot set properties of null (setting ‘dev’)</h4><p>This error can be caused by several things.</p><p><strong>Solution 1:<br></strong>Begin with deleting all files in node_modules\@suzieq . To recreate the contents, just run npm install .</p><p>Verify the folder node_modules\@suzieqwas created without errors.</p><p><strong>Solution 2:<br></strong>A: Inside the apple-package:s folder, open package.json . Either devDependencies or dependencies is broken.</p><p><strong>Solution 3:<br></strong>Ensure that all the “name” properties in package.json files has unique names.</p><h4>When using tsc, it produces .js files in my src-folders</h4><p>The files section is missing in tsconfig.json . See above.</p><pre>&quot;files&quot;: [<br>    &quot;./src/index.ts&quot;<br>]</pre><h3>Demo repository?</h3><p>Yes, there is one. See <a href="https://github.com/tomnil/monorepoplate">https://github.com/tomnil/monorepoplate</a></p><h3>Enjoy :)</h3><h4>Further Reading</h4><p><a href="https://bit.cloud/blog/painless-monorepo-dependency-management-with-bit-l4f9fzyw">Painless monorepo dependency management with Bit</a></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em>, and</em></strong><em> </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong><em> Interested in Growth Hacking? Check out </em><a href="https://circuit.ooo/"><strong><em>Circuit</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90b329ba7275" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/monorepo-setup-with-npm-and-typescript-90b329ba7275">Monorepo Setup with NPM and TypeScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up an API with JWT, req.User and Route Security]]></title>
            <link>https://javascript.plainenglish.io/how-to-set-up-an-api-with-jwt-req-user-and-route-security-52f8da08cda6?source=rss-fffaf8ff7bac------2</link>
            <guid isPermaLink="false">https://medium.com/p/52f8da08cda6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Tomas Nilsson]]></dc:creator>
            <pubDate>Mon, 27 Sep 2021 07:03:10 GMT</pubDate>
            <atom:updated>2021-09-27T07:03:10.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DB8xdKp5VWAG-6dC" /><figcaption>Photo by <a href="https://unsplash.com/@frenchriera?utm_source=medium&amp;utm_medium=referral">Anthony Riera</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>After reading this article, you’ll understand how to create an API in Node.js/TypeScript with functions such as:</p><ul><li>On calling /login, generate and return a Bearer/JWT to the user</li><li>Use middleware to decode the Authentication header (Bearer/JWT)</li><li>Modify the Express namespace to add support for req.User</li><li>Add security on routes (ie, “Only Admin may access this Route”)</li></ul><p><strong><em>PS: There is a link to a working git at the very end.</em></strong></p><h3>Basic Express setup</h3><p>There are very few exciting things about something that has been documented a thousand times, but we need to get through this part:</p><pre>import Express from &#39;express&#39;;<br>import http from &#39;http&#39;;<br>import cors from &#39;cors&#39;;</pre><pre>const PORT = process.env.PORT !== undefined ? parseInt(process.env.PORT) : 3001;</pre><pre>let app: Express.Application | undefined = undefined;</pre><pre>app = Express();</pre><pre>app.use(cors({ exposedHeaders: &#39;Authorization&#39; }));<br>app.use(Express.urlencoded({ extended: true }));<br>app.use(Express.json());</pre><pre><strong>// -----&gt; MORE CODE WILL BE ADDED HERE! &lt;--------</strong></pre><pre>http.createServer(app).listen(PORT, () =&gt; console.log(`Webserver running at <a href="http://localhost:${PORT}/`">http://localhost:${PORT}/`</a>));</pre><p>Add all routes at the line shown above in the order they’re presented. Add the rest of the code somewhere else. A few items should be in their own file(s).</p><h3>Decoding the JWT</h3><p>Really early in the routes, the function for decoding the header should be found. If there are truly anonymous routes present (like /robots.txt , then this function should probably come after that).</p><pre>app.use(function JWTDecoderMiddleware(req: Express.Request, res: Express.Response, next: Express.NextFunction) {</pre><pre>  const authorization = req.headers.authorization;<br>  if (authorization &amp;&amp; authorization.startsWith(&quot;Bearer &quot;)) {<br>     const u = DecodeJWT(authorization.substring(7));<br>     if (u)<br>        req.User = u;<br>     else<br>        console.log(&quot;jwt found, but it was not valid.&quot;);<br>  }</pre><pre>next();<br>    });</pre><p>This function is dependant on two things; the global namespace being modified making req.User available and the DecodeJWT -function (see below)</p><h4>The `User`, `Bearer` and `AccessLevel` types</h4><p>Before continuing, there are a couple of types needed. At the API side, we will have some kind of user logged in, and the type/interface for that needs to be handled.</p><p>Next, the Bearer. It will be sent to and stored by <em>the client</em> (in the encrypted JWT format). Basically, anything non-sensitive can be stored in the JWT, just be aware that the user can <em>easily </em>decrypt the JWT (but <strong>they cannot modify it</strong>). Examine JWT at <a href="https://jwt.io/">https://jwt.io/</a>.</p><p><strong>types.ts</strong></p><pre>export type User = {<br>    ID: string,<br>    Name: string,<br>    AccessLevel: AccessLevel,</pre><pre>    /** Never ever store an clear-text pw like this! */<br>    Password: string<br>}</pre><pre><br>export type Bearer = {<br>    Name: string,<br>    ID: string,<br>    AccessLevel: AccessLevel<br>}</pre><pre>export type AccessLevel = &quot;Admin&quot; | &quot;User&quot; | &quot;Anonymous&quot;;</pre><p>❕ <strong>Store the user&#39;s credentials in a safe way, don’t ever use clear text passwords as in this demo.</strong></p><p><strong>global.d.ts</strong></p><p>Note the global.d.ts naming. Read more about global variables in <a href="https://javascript.plainenglish.io/typescript-and-global-variables-in-node-js-59c4bf40cb31">https://javascript.plainenglish.io/typescript-and-global-variables-in-node-js-59c4bf40cb31</a></p><p>At the same time as Express.User is added, we add the types for the environment variables that we intend to use:</p><pre>import { User } from &#39;./types&#39;;</pre><pre>declare global {</pre><pre><strong>    namespace Express {<br>        interface Request {<br>            User: User<br>        }<br>    }</strong></pre><pre>    namespace NodeJS {<br>        interface ProcessEnv {<br>          JWTENCRYPTIONKEY: string;<br>          NODE_ENV: &#39;development&#39; | &#39;production&#39;;<br>          PORT: string;  // All environment variables are strings<br>       }<br>    }<br>}</pre><pre>export { };</pre><p>❕ Make sure you either use .env or set the environment variables.</p><h4>The DecodeJWT function</h4><p>In order to verify the JWT hasn’t been tampered with, the API must define a secret key. Basically decode it as:</p><pre>import * as jsonwebtoken from &quot;jsonwebtoken&quot;;</pre><pre>export function Decode&lt;T extends object&gt;(iJWT: string): T | undefined {<br>    try {<br>        return jsonwebtoken.verify(iJWT,<br>                process.env.JWTENCRYPTIONKEY) as T;<br>    } catch (e) {<br>        return undefined;<br>    }<br>}</pre><pre>export function DecodeJWT(jwt: string): User | undefined {</pre><pre>    const decoded = Decode&lt;<strong>Bearer</strong>&gt;(jwt);<br>    if (decoded)<br>        return Users.find(u =&gt; u.ID === decoded.ID);<br>}</pre><h4>Users?</h4><p>We need some users.</p><pre>const Users: User[] = [<br>   { ID: &quot;root&quot;, Name: &quot;root&quot;, AccessLevel: &quot;Admin&quot;, Password: &quot;Banana1&quot; },<br>   { ID: &quot;foo&quot;, Name: &quot;Foo&quot;, AccessLevel: &quot;User&quot;, Password: &quot;Bar&quot; }<br>];</pre><p>❕ <strong>Store the user&#39;s credentials in a safe way, don’t ever use clear text passwords as in this demo.</strong></p><h3>Route /</h3><p>Let’s add some routes, beginning with / .</p><pre>app.get(&#39;/&#39;, function (req: Express.Request, res: Express.Response){<br>     res.status(200).json({<br>         &quot;Foo&quot;: &quot;Bar&quot;,<br>         &quot;Time&quot;: new Date().toISOString()<br>     });<br> });</pre><h3>Route /login</h3><p>This route will take the { &quot;username&quot;: &quot;Foo&quot;, &quot;password&quot; : &quot;Bar&quot; } and try to find a user matching the credentials. If found, a JWT is generated and sent to the callee.</p><pre>app.post(&#39;/login&#39;, function (req: Express.Request, res: Express.Response) {</pre><pre>    console.log(`U=${req.body.username}, Pwd=&lt;hidden&gt;`);</pre><pre>    const jwt = Login(req.body);<br>    if (jwt) {<br>      res.append(&#39;Authorization&#39;, jwt);<br>      res.status(200).json({ Success: true, JWT: jwt });<br>    }<br>    else<br>       res.status(200).json({ Success: false });</pre><pre>});</pre><h4>Login</h4><pre>export function Login(arg: { username: string, password: string }): string | undefined {</pre><pre>    const user = Users.find(u =&gt; u.Name === arg.username <br>     &amp;&amp; u.Password === arg.password);<br>    if (user) {</pre><pre>        const result: Bearer = {<br>            ID: user.ID,<br>            Name: user.Name,<br>            AccessLevel: user.AccessLevel<br>        };</pre><pre>       return Encode(result);</pre><pre>    }<br>}</pre><h4>Encode function</h4><pre>export function Encode&lt;T extends object&gt;(iPayLoad: T, iTimeoutSeconds = 3600 * 10): string {<br>    return jsonwebtoken.sign(<br>                     iPayLoad, <br>                     process.env.JWTENCRYPTIONKEY, <br>                     { expiresIn: iTimeoutSeconds }<br>                   );<br>}</pre><h3>So far, so good.</h3><p>At this point, we have achieved a running web server that exposes / , /login and that can decode any valid JWT and through that can return a User.</p><p>Now it gets a little bit more complicated. :)</p><h3>HasAccessLevel — implemented as a function</h3><p>Checking accesslevel can be done with a function or as Middleware.</p><h4>/me — with a function to check accesslevel</h4><pre>app.get(&#39;/me&#39;, function (req: Express.Request, res: Express.Response) {</pre><pre>  <strong> if (!HasAccessLevel(req, res, [&quot;User&quot;, &quot;Admin&quot;])) <br>      return;  // Response has already been sent</strong></pre><pre>   res.status(200).json({ &quot;UserName&quot;: req.User.Name });</pre><pre>});</pre><h4>HasAccessLevel function</h4><p>AccessLevel is a type, defined as type AccessLevel = &quot;Admin&quot; | &quot;User&quot; | &quot;Anonymous .</p><pre>function HasAccessLevel(req: Express.Request, res: Express.Response, iReqLevel: AccessLevel[] = []): boolean {</pre><pre>    let result = false;<br>    if (req.User)  // Has the middleware decoded the jwt properly?<br>        // Yes, does the user match?<br>        result = iReqLevel.includes(req.User.AccessLevel);<br>    else<br>       // No, but maybe &quot;Anonymous&quot; can access this function?<br>       result = iReqLevel.includes(&quot;Anonymous&quot;);</pre><pre><br>     // Not allowed to access? Send 401!<br>     if (!result) {<br>        res.status(401).json(<br>                { Success: false, Error: &quot;Access denied&quot; });<br>        res.end();<br>    }</pre><pre>    return result;<br>}</pre><h3>HasAccessLevelMiddleware — implemented as Middleware</h3><h4>/me — using middleware</h4><p>Middlewares has to have three parameters, but that can easily be avoided with the following syntax:</p><pre>app.get(&#39;/me2&#39;,<br>       <strong>(rq, rs, n) =&gt; HasAccessLevelMiddleware(rq, rs, n, [&quot;User&quot;, &quot;Admin&quot;]),</strong> <br>   (req: Express.Request, res: Express.Response) =&gt; {</pre><pre>    // Will only get here if HasAccessLevelMiddleware allows it<br>    res.status(200).json({ &quot;UserName&quot;: req.User.Name });</pre><pre>});</pre><h4>HasAccessLevelMiddleware</h4><p>The middleware decides if next() is called, or not.</p><pre>export function HasAccessLevelMiddleware(req: Express.Request, res: Express.Response, next: Express.NextFunction, iReqLevel: AccessLevel[] = []): void {</pre><pre>    let hasAccess = false;<br>    if (req.User)  // Has the middleware decoded the jwt properly?<br>       hasAccess = iReqLevel.includes(req.User.AccessLevel);<br>    else<br>       hasAccess = iReqLevel.includes(&quot;Anonymous&quot;);</pre><pre><strong>    if (hasAccess)<br>       next();   // Continue executing</strong><br>    else {<br>       res.status(401).json({ Success: false, Error: &quot;Denied&quot; });<br>       res.end();<br>    }<br>}</pre><h3>Error handler</h3><p>At last, add the error handler. The error handler takes four parameters, where the first one is err . To get TypeScript to shine, it’s a good thing to define err as Error &amp; { status: number, message: string } . Error is the built-in Error object and Express adds the status and message .</p><pre>app.use(function (<strong>err: Error &amp; { status: number, message: string }</strong>, req: Express.Request, res: Express.Response, next: Express.NextFunction) {</pre><pre>console.error(err.status);<br>  console.error(err.message);<br>  console.error(err.stack);<br>  res.status(500).json({ Error: &quot;Internal error&quot; });<br>  res.end();</pre><pre>});</pre><h3>curl</h3><p>These commands were written on Windows, make necessary adjustments to run on other platforms:</p><pre># Login as user &quot;Foo&quot;</pre><pre>curl -X POST -H &quot;Content-Type: application/json&quot; -d &quot;{\&quot;username\&quot;:\&quot;Foo\&quot;,\&quot;password\&quot;:\&quot;Bar\&quot;}&quot; http://localhost:3001/login</pre><pre># Grab token from body or headers and do:</pre><pre>set TOKEN=eyJhbGciOiJIUzI1NiIsIn.....</pre><pre># Use the token</pre><pre>curl -H &quot;Authorization: Bearer %TOKEN%&quot; http://localhost:3001/me</pre><h3>Git repo</h3><p>The repo is prepared to just run by pressing F5 in VSCode (or nodemon , or by running node ). Read more on <a href="https://github.com/tomnil/expressplate">https://github.com/tomnil/expressplate</a></p><h3>Enjoy :)</h3><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52f8da08cda6" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-set-up-an-api-with-jwt-req-user-and-route-security-52f8da08cda6">How to Set Up an API with JWT, req.User and Route Security</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Typed Express Request and Response with TypeScript]]></title>
            <link>https://javascript.plainenglish.io/typed-express-request-and-response-with-typescript-7277aea028c?source=rss-fffaf8ff7bac------2</link>
            <guid isPermaLink="false">https://medium.com/p/7277aea028c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tomas Nilsson]]></dc:creator>
            <pubDate>Thu, 23 Sep 2021 14:46:06 GMT</pubDate>
            <atom:updated>2024-07-22T07:26:07.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v_mDTJ6cXotRWyQj" /><figcaption>Photo by <a href="https://unsplash.com/@jefflssantos?utm_source=medium&amp;utm_medium=referral">Jefferson Santos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Writing code with TypeScript is great, but there are some places in the code where it’s really tricky to let TypeScript shine. One of them is when defining routes in Express.</p><p>This article goes through some of the ways to add TypeScript to the Express.Request and Express.Response objects.</p><h3>Setting up Express</h3><p>Let’s do the basic stuff first.</p><pre>import Express from &#39;express&#39;;<br>import http from &#39;http&#39;;</pre><pre>let app: Express.Application | undefined = undefined;</pre><pre>export function InitializeExpress(port = 3001): void {</pre><pre>    app = Express();<br>    app.use(Express.urlencoded({ extended: true }));</pre><pre>    app.get(&#39;/&#39;, function (_req: Express.Request, res: Express.Response) {<br>        res.status(200).json(<strong>{<br>            &quot;Foo&quot;: &quot;Bar&quot;,<br>             &quot;Time&quot;: new Date().toISOString()<br>        }</strong>);<br>    });</pre><pre>   // Add 404 handler<br>   app.use(function (_req: Express.Request, res: Express.Response) {<br>      res.status(404).send(&quot;Not found&quot;);<br>   });</pre><pre>   // Start server (app.listen can also be used)    <br>   http.createServer(app).listen(port, () =&gt;  <br>    console.log(`Running at <a href="http://localhost:${port}/`">http://localhost:${port}/`</a>));</pre><pre>}</pre><p>On accessing <a href="http://localhost:3001/">http://localhost:3001/</a>, this server will return something like:</p><pre>{&quot;Foo&quot;:&quot;Bar&quot;,&quot;Time&quot;:&quot;2021-09-21T19:32:15.091Z&quot;}</pre><h3><strong>Express.Request.body</strong></h3><p>The Express.Request object is defined as:</p><pre>interface e.Request&lt;P = ParamsDictionary, <strong>ResBody = any</strong>, ReqBody = any, ReqQuery = QueryString.ParsedQs, Locals extends Record&lt;string, any&gt; = Record&lt;string, any&gt;&gt;</pre><p>and this type is complex to use. To simplify this, a new type is defined as:</p><pre>export interface TypedRequestBody&lt;T&gt; extends Express.Request {<br>    body: T<br>}</pre><p>With this new interface it’s possible to use generics to type the body:</p><pre>app.post(&#39;/login&#39;, function (req: <strong>TypedRequestBody&lt;{ username: string, password: string }&gt;</strong>, res: Express.Response) {</pre><pre>    const success = req.body.username === &quot;foo&quot;<br>                    &amp;&amp; req.body.password === &quot;bar&quot;;</pre><pre>    res.status(200).json({ &quot;Success&quot;: success });<br>});</pre><blockquote>This will give the TypeScript checking as well as the intellisense:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*sxXonOoLHnjO2l76WvDP5w.gif" /></figure><blockquote><em>💡 </em>Speed up your blog creation with <a href="https://differ.blog/differ-ai"><strong><em>DifferAI</em></strong></a>.</blockquote><blockquote>Available for <strong><em>free</em> </strong>exclusively on the <strong><em>free and open blogging platform, </em></strong><a href="https://differ.blog/"><strong><em>Differ</em></strong></a><strong>.</strong></blockquote><p><a href="https://differ.blog/differ-ai">Introducing DifferAI</a></p><h3>Express.Request .query</h3><p>Modifying the query in Express.Request is somewhat more tricky, because Express uses types from express-serve-static-core , which in turn Express doesn’t expose. So the only way to get hold of the proper types is to import { Query } from &#39;express-static-serve-core&#39;; . The solution is to do:</p><pre>import { Query } from &#39;express-serve-static-core&#39;;</pre><pre>export interface TypedRequestQuery&lt;T extends Query&gt; extends Express.Request {</pre><pre>     query: T</pre><pre>}</pre><p>To use it it would look something like:</p><pre>app.get(&#39;/article/:id&#39;, function (req: <strong>TypedRequestQuery&lt;{ id: string }</strong>&gt;, res: Express.Response) {</pre><pre>    const id = req.query.id;</pre><pre>    // Fetch from database here and return article        </pre><pre>    res.status(200).json({ ID: id });</pre><pre>});</pre><h3>Express.Request .body &amp; query</h3><p>Let’s do another type where <em>both </em>body and query can be typed:</p><pre>export interface TypedRequest&lt;T extends Query, U&gt; extends Express.Request {<br>    body: U,<br>    query: T<br>}</pre><p>The usage could look something like:</p><pre>app.put(&#39;/article/:id&#39;, function (req: <strong>TypedRequest&lt;{ id: string }, { name: string }&gt;</strong>, res: Express.Response) {</pre><pre>        console.log(`Updating article<strong> ${req.query.id}</strong>`);<br>        console.log(`setting name to <strong>${req.body.name}</strong>`);<br>        res.status(200).json({ Success: true });</pre><pre>});</pre><h3>A small security note on incoming requests</h3><p>TypeScript doesn’t exist at runtime so even the code is setup to expect a payload of:</p><pre>{ username: string, password: string }</pre><p>... bad payloads such as this one:</p><pre>{ username: undefined, password: [&quot;Hello&quot;, &quot;World&quot;] }</pre><p>.. can be submitted in order to “mess” with the route. Therefore, <strong>always make sure to <em>always</em> validate the incoming payload</strong>.</p><h4>PS:</h4><p>If you want to automatically generate validator functions from TypeScript interfaces / Types, then read this article: <a href="https://javascript.plainenglish.io/how-to-automatically-convert-typescript-types-to-runtime-validators-5b06ee269b13">https://javascript.plainenglish.io/how-to-automatically-convert-typescript-types-to-runtime-validators-5b06ee269b13</a></p><h3>Express.Response</h3><p>Again Express uses types from express-serve-static-core :</p><pre>import { Send } from &#39;express-serve-static-core&#39;;</pre><p>The interface is defined as:</p><pre>export interface TypedResponse&lt;ResBody&gt; extends Express.Response {</pre><pre>   json: Send&lt;ResBody, this&gt;;</pre><pre>}</pre><p>Usage could look something like:</p><pre>app.get(&#39;/ping&#39;, function (_req: Express.Request, res: <strong>TypedResponse&lt;{ Pong: string }&gt;</strong>) {</pre><pre>     res.status(200).json(<strong>{ &quot;Pong&quot;: new Date().toISOString() }</strong>);</pre><pre>});</pre><p>And again, if the format of the response doesn’t match the expected result, TypeScript/VSCode (ErrorLens) will inform with an error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M8Aj0DmK1FmpTpzMpJoXDw.gif" /></figure><h3>Demo source code?</h3><p><a href="https://github.com/tomnil/typedexpress">https://github.com/tomnil/typedexpress</a></p><h3>Enjoy :)</h3><h4>Further Reading</h4><p><a href="https://bit.cloud/blog/sharing-types-between-your-frontend-and-backend-applications-l5qih48g">Sharing Types Between Your Frontend and Backend Applications</a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7277aea028c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/typed-express-request-and-response-with-typescript-7277aea028c">Typed Express Request and Response with TypeScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Hooks Demystified]]></title>
            <link>https://javascript.plainenglish.io/react-hooks-demystified-2a8370076b82?source=rss-fffaf8ff7bac------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a8370076b82</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Tomas Nilsson]]></dc:creator>
            <pubDate>Tue, 21 Sep 2021 13:24:19 GMT</pubDate>
            <atom:updated>2021-09-21T13:24:19.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MxEYg2sbfJc5YK9s" /><figcaption>Photo by <a href="https://unsplash.com/@cgower?utm_source=medium&amp;utm_medium=referral">Christopher Gower</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>React Hooks is really cool, but it’s not a matter of magic. This article will go through the basics and hopefully make some things clearer.</p><h3>What is a hook, anyway?</h3><p>Well, to explain that it’s much simpler to compare to something that’s known. So, a typical component returns JSX as in this example:</p><pre>import React from &#39;react&#39;;</pre><pre>const Comp1 = (): JSX.Element =&gt; {<br>  <strong> return &lt;h1&gt;The time is {new Date().toISOString()}&lt;/h1&gt;;</strong><br>};</pre><pre>export default Comp1;</pre><p>So what about hooks? <strong>Well they return variables and functions </strong>rather than JSX.</p><blockquote><strong>A compontent returns JSX and a a hook returns (one or more) functions, variables or objects.</strong></blockquote><p>OK, seems easy. But why not use a module then? Something like:</p><pre>export function Sum(number1: number, number2: number): number { <br>  return number1 + number2;<br>};</pre><p>Because modules cannot “interact” with React; hooks are built to access React features such as useState . Read more about this at the very end of the article.</p><p>Now, let’s dive into some examples.</p><h3>Hook example — useCounter</h3><p>Consider the follwoing code. It returns a number and a function (named “increment”).</p><pre>import React from &#39;react&#39;;</pre><pre>const useCounter = (): [number, () =&gt; void] =&gt; {</pre><pre>     const [number, setNumber] = React.useState(0);</pre><pre>     function increment() {<br>        setNumber(randomNumber =&gt; randomNumber + 1);<br>     }</pre><pre>  <strong>   return [number, increment];</strong></pre><pre>};</pre><pre>export default useCounter;</pre><p>The entire code to use it is:</p><pre>import React from &#39;react&#39;;<br><strong>import useCounter from &#39;./usecounter&#39;;</strong></pre><pre>function Hook1Example() {</pre><pre><strong>  // Grab the number and the increment-function<br>  const [number, inc] = useCounter();</strong></pre><pre>return &lt;&gt;<br>    Number: <strong>{number}</strong><br>    &lt;button <strong>onClick={inc}</strong>&gt;Increment&lt;/button&gt;<br>  &lt;/&gt;</pre><pre>}</pre><pre>export default Hook1Example;</pre><p>In their most simple example, hooks are basically just this.</p><h3>Hook example — useIsWeekEnd</h3><p>The number of parameters returned from a hook can be arbitrary and the way parameters are returned can also be changed. Let&#39;s show it with examples:</p><h4>As an Array:</h4><p>…in this case, as a number and a function.</p><pre>import React from &#39;react&#39;;</pre><pre>const useCounter = ()<strong>: [number, () =&gt; void]</strong> =&gt; {</pre><pre>    const [number, setNumber] = React.useState(0);</pre><pre>    function increment() {<br>        setNumber(randomNumber =&gt; randomNumber + 1);<br>    }</pre><pre><strong>    return [number, increment];</strong></pre><pre>};</pre><pre>export default useCounter;</pre><h4>As a single item:</h4><p>… in this case, a boolean:</p><pre>import React from &#39;react&#39;;</pre><pre>const useIsWeekend = ()<strong>: boolean</strong> =&gt; {</pre><pre>   const [isWeekEnd, setIsWeekEnd] = React.useState&lt;boolean&gt;(false);</pre><pre>   React.useEffect(() =&gt; {<br>      setIsWeekEnd([6, 0].includes(new Date().getDay()))<br>   }, []);</pre><pre>  <strong> return isWeekEnd;</strong></pre><pre>};</pre><pre>export default useIsWeekend;</pre><h4>As an object:</h4><p>…perfect for destructuring :)</p><pre>import React from &#39;react&#39;;</pre><pre>const useCalculator = (): <strong>{ result: number; Add: (i: number) =&gt; void; Set: (i: number) =&gt; void; }</strong> =&gt; {</pre><pre>const [result, setResult] = React.useState(0);</pre><pre>     function Add(i: number) {<br>        setResult(result =&gt; result + i);<br>    }</pre><pre>     function Set(i: number) {<br>        setResult(result);<br>    }</pre><pre>  <strong>  return { result, Add, Set }</strong></pre><pre>};</pre><pre>export default useCalculator;</pre><p>And the component:</p><pre>import React from &#39;react&#39;;<br>import useCalculator from &#39;./usecalculator&#39;;</pre><pre>function Hook2() {</pre><pre><strong>  const { result, Add, Set } = useCalculator()</strong></pre><pre>  return &lt;&gt;<br>      Result: {result}&lt;br /&gt;<br>      &lt;button onClick={() =&gt; Add(1)}&gt;Increment&lt;/button&gt;<br>      &lt;button onClick={() =&gt; Add(-1)}&gt;Decrement&lt;/button&gt;<br>      &lt;button onClick={() =&gt; Set(0)}&gt;Reset&lt;/button&gt;<br>      &lt;/&gt;</pre><pre>}</pre><pre>export default Hook2;</pre><h3>Hook Example — useIsLucky</h3><p>As with components, a hook may trigger a rerender. Conside the following example:</p><pre>import React from &#39;react&#39;;</pre><pre>const useIsLucky = (userID: string): [boolean | undefined] =&gt; {</pre><pre>    const [isLucky, setIsLucky] = React.useState&lt;boolean | undefined&gt;(undefined);</pre><pre>   React.useEffect(() =&gt; {</pre><pre><strong>         // Fake a call to the API where the user<br>         // is checked if they&#39;re lucky<br>        setTimeout(() =&gt; {<br>            setIsLucky(Math.random() &gt; 0.5)<br>        }, 1000);</strong></pre><pre>}, [userID]);</pre><pre>    return [isLucky];</pre><pre>};</pre><pre>export default useIsLucky;</pre><p>And the component:</p><pre>import React from &#39;react&#39;;<br>import useIsLucky from &#39;./useislucky&#39;;</pre><pre>function Example5() {</pre><pre><strong>  const [result] = useIsLucky(&quot;Tomas&quot;);</strong></pre><pre>  if (result !== undefined)<br>    return &lt;&gt;Was lucky? {result ? &quot;Yes&quot; : &quot;No&quot;}&lt;/&gt;<br>  else<br>    return &lt;&gt;Loading..&lt;/&gt;</pre><pre>}</pre><pre>export default Example5;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*mzE_Tc0PIy18yTKze7H9og.gif" /></figure><h3>Functions vs Hooks!</h3><p>Alright, the basics of hooks are covered. But before letting go, there’s one more thing that needs to be covered:</p><blockquote>When should hooks be used and when should ordinary modules (eg, .ts-files with code) be used?</blockquote><p>Well, it boils down to the dependency of React. Consider the following code where no dependencies for React can be found. Alright, it’s <em>named</em> useSumHook, but in reality, it’s not a hook.</p><pre>const useSumHook = (number1: number, number2: number): number =&gt; {<br>   return number1+number2;<br>};</pre><pre>export default useSumHook;</pre><p>Me personally, I’d store this function in a .ts-file as:</p><pre>export function Sum(number1: number, number2: number): number { <br>  return number1 + number2;<br>};</pre><p>and then use it as:</p><pre>import { Sum } from &#39;./misc&#39;;</pre><h4>Git repo</h4><p>It’s not pretty, but it’s useful. <a href="https://github.com/tomnil/hooksexample">https://github.com/tomnil/hooksexample</a></p><h3>Enjoy :)</h3><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a8370076b82" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/react-hooks-demystified-2a8370076b82">React Hooks Demystified</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Convert Node.js Code from JavaScript to TypeScript]]></title>
            <link>https://javascript.plainenglish.io/how-to-convert-node-js-code-from-javascript-to-typescript-8e7d031a8f49?source=rss-fffaf8ff7bac------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e7d031a8f49</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Tomas Nilsson]]></dc:creator>
            <pubDate>Mon, 13 Sep 2021 10:58:19 GMT</pubDate>
            <atom:updated>2021-09-13T10:58:19.477Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eX32sidkE5hMsVhw" /><figcaption>Photo by <a href="https://unsplash.com/@baciutudor?utm_source=medium&amp;utm_medium=referral">Tudor Baciu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>This guide contains a lot of information on how to begin converting an existing JavaScript project to TypeScript.</p><h4>Step-by-step approach…</h4><p>This document begins with establishing a project (still in JavaScript) with a TypeScript “compile-no-errors” setup (retaining all files as .js). One step at a time, we’ll then resolve the found issues and finally become TypeScript-only (.ts-only).</p><p>I would recommend reading this document twice. First to establish a list of all todo’s, and second to actually work on them. There are so many things that are very important (“this should be at the very top of the document”), but it’s not really feasible.</p><h4>Some TypeScript basics</h4><p>If you’ve never worked with TypeScript, it will be an additional layer of challenges. There’s a couple of important “mentions” that needs to be done:</p><ul><li>TypeScript only exists at “compile” time, at runtime it’s still JavaScript</li><li>TypeScript doesn’t really compile, it transpiles.</li><li>The TypeScript transpiler is named “tsc”</li><li>node (node.exe) can only run JavaScript code, but by adding the “plugin” ts-node, typescript support is achieved.</li><li>VSCode has great support for TypeScript, and so does ESLint (with the correct plugin)</li></ul><p>Most important is probably this: <em>Running</em> the code and <em>transpiling</em> the code are two different things. You’ll need to make both worlds work.</p><p>If you want to check out a working (empty) project then check out <a href="https://github.com/tomnil/emptyts">https://github.com/tomnil/emptyts</a>.</p><h4>Types…</h4><p>While there are tips on resolving common TypeScript issues, there’s little information here on how to actually write types. Still, a couple of tips can be important.</p><p><strong>any</strong></p><p>Any basically disables type checking for a variable (read: makes it “JavaScript”). any should be avoided, but is very usable in some scenarios.</p><pre>let a : any = {}<br>a.name = &quot;Sarah&quot;;   // TypeScript checking is disabled here</pre><p><strong>unknown</strong></p><p>unknown and any are “remote friends”, but unknown doesn’t allow accessing properties by their name.</p><pre>let myBox: unknown = {};       // OK!<br>myBox = { foo: &quot;bar&quot; };        // OK!<br>console.log(myBox.foo);        // Error<br>myBox.foo = &quot;FooBar&quot;;          // Error</pre><p><strong>Objects</strong></p><p>Either way works:</p><pre>let user1: <strong>{ Name: string, Age: number };</strong><br>user1 = { Name: &quot;John&quot;, Age: 16 };<br>console.log(user1.Name);</pre><pre><strong>type User = { Name: string, Age: number };</strong><br>let user2: User = { Name: John&quot;, Age: 16 };<br>console.log(user2.Name);</pre><p>Now, with the basic stuff out of the way, let’s begin converting.</p><h3>Establishing the toolchain</h3><p>There’s a number of tools that must to be in place to be able to work with TypeScript. There are also a number of tools that make it easier :)</p><h4>tsc + typescript</h4><p>Begin with making a global install of tsc(the transpiler) and typescript itself.</p><pre>npm install tsc -g</pre><pre>npm install typescript --save-dev</pre><h4>ts-node</h4><p>ts-node is the module that adds support for running TypeScript directly (that is; <em>not</em><strong><em> </em></strong>first compiling from .ts to .js and then run .js. ts-node can run .ts directly).</p><p>This tool must be installed locally.</p><pre>npm install ts-node --save-dev</pre><h4>typesync (optional)</h4><p>A great tool for automatically downloading definition files for all your referenced modules (where it’s not built-in into the module you’ve referenced). Install with npm.</p><pre>npm install -g typesync</pre><h4>eslint (optional)</h4><p>eslint is equally important, but not covered by this document.</p><h3>Configuring your project for TypeScript</h3><h4>Create tsconfig.json</h4><p>In the root of the project, create tsconfig.json. Begin with this content:</p><pre>{<br>  &quot;compilerOptions&quot;: { /* Docs: <a href="https://www.typescriptlang.org/tsconfig">https://www.typescriptlang.org/tsconfig</a> */<br>    &quot;target&quot;: &quot;ES2020&quot;,<br>    &quot;module&quot;: &quot;commonjs&quot;,<br>    &quot;outDir&quot;: &quot;bin&quot;,<br>    &quot;rootDir&quot;: &quot;src&quot;,<br>    &quot;strict&quot;: true,<br>    &quot;noImplicitAny&quot;: false,<br>    &quot;strictNullChecks&quot;: true,<br>    &quot;checkJs&quot;: true,<br>    &quot;allowJs&quot;: true,<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;types&quot;: [<br>      &quot;node&quot;<br>    ],<br>    &quot;lib&quot;: [<br>      &quot;es6&quot;<br>    ],<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;forceConsistentCasingInFileNames&quot;: true,<br>    &quot;allowUnreachableCode&quot;: true,<br>     &quot;useUnknownInCatchVariables&quot;: false,  // TypeScript 4.4+ only!<br>},<br>  &quot;include&quot;: [<br>    &quot;src/**/*.ts&quot;,<br>    &quot;src/**/*.js&quot;<br>  ],<br>  &quot;exclude&quot;: [<br>    &quot;node_modules&quot;,<br>    &quot;&lt;node_internals&gt;/**&quot;,<br>  ]<br>}</pre><p>Change include and exclude accordingly (note, these settings will <strong><em>not </em></strong>be used by some tools unless the environment variable TS_NODE_FILES is set to true ).</p><h4>Some quick notes on the config settings</h4><p><strong>“target”: “ES2020”</strong></p><p>If you’re doing backend development then it’s most logical to use as new EcmaScript version as possible.</p><p><strong>“rootDir”: “src”</strong></p><p>If you follow most standards, your source code is in “src”</p><p><strong>“outDir”: “out”</strong></p><p>Typescript is build around “compiling” (really transpiling) from the /src/ folder into a destination directory /out/.</p><p>This guide avoids using the /out/ folder since it really slows down the development and debugging process. Running the code as-is (as .ts) is much more efficient. Still, the “outDir” must be set.</p><p><strong>“allowJs” — transpiling javascript files</strong></p><p>Turn on allowJs and checkJs if you want .js files to be treated to .ts-files. Also, make sure both .ts and .js is included in the include section.</p><pre>&quot;include&quot;: [<br>        &quot;src/**/*.ts&quot;,<br>        &quot;src/**/*.js&quot;<br>    ],</pre><p>“<strong>useUnknownInCatchVariables</strong>”</p><p>This is a new setting beginning with TypeScript 4.4. Per default it’s set to true, which means the error in catch will be unknown , and per default it’s impossible to access .message .</p><p>The easy fix is to (, for now, set useUnknownInCatchVariables to false , or to make a proper fix as. See below for more information on this topic.</p><h4>.gitignore out-folder</h4><p>Using git? Modify .gitignore to exclude the out folder and temporary files from tsc .</p><pre>out/<br># TS -incremental file<br>tsconfig.tsbuildinfo<br>node_modules</pre><h4>Removing the folder “out” from search results</h4><p>In .vscode/settings.json, use the following settings:</p><pre>{<br>  &quot;search.exclude&quot;: {<br>     &quot;**/node_modules&quot;: true,<br>     &quot;**/package-lock.json&quot;: true,<br>     &quot;**/package.json&quot;: true,<br>     &quot;out/**&quot;: true // Don&#39;t search the TypeScript &quot;out&quot; folder<br>   }<br>}</pre><h4>vscode: Reload the window to ensure proper loading of tsconfig.json</h4><p>vscode will process tsconfig.jsonbut it’s probably a good idea to reload vscode at this time: Press ctrl-shift-p and search for the command `Developer: reload window`.</p><h3>Add existing types</h3><p>Types for modules installed from the npm registry can be resolved through four different ways:</p><ul><li>The types are included from the module owner</li><li>The types can be installed seperately</li><li>Manually write the missing types</li><li>Set the module to be “any”</li></ul><p>typesync is a cool tool that detects missing types (if not found, install it with npm)</p><pre>&gt; typesync</pre><pre>📦 projectname — package.json (1 new typings added, 0 unused typings removed)<br>└─ + @types/<strong>packagename1</strong></pre><pre>✨  Go ahead and run npm install or yarn to install the packages that were added.</pre><pre>&gt; npm install</pre><p>If you cannot find needed types, there are only two ways left to fix it. Either you write the types yourself or you declare the <em>entire </em>module as any. The latter is often most easy: Create a file in the root named “declarations.d.ts” and allow it to contain <strong>just</strong> “declare module” statements (<strong>nothing else </strong>or it will stop working).</p><pre>declare module &#39;excel4node&#39;;</pre><p>If you want some information on how to write types, check out <a href="https://github.com/DefinitelyTyped/DefinitelyTyped">https://github.com/DefinitelyTyped/DefinitelyTyped</a>.</p><h4>Setting types on variables</h4><p>As stated, this guide is not a TypeScript guide. But giving a hint is probably a good thing. There are three ways to assign a type to a variable:</p><pre>type User = { Name: string, Age: number };</pre><pre>let a : User | undefined = undefined;<br>let b = &lt;User&gt;{ Name: &quot;Karin&quot;, Age: 40 };   // Type Assertion<br>let c = { Name: &quot;Karin&quot;, Age: 40 } as User; // Type Assertion</pre><h3>Transpiling and deciding how to fix errors</h3><p>On the first TypeScript transpile your current javascript files are almost guranteed to generate a ton of warnings and errors. Before even attempting to switch to TypeScript, it’s a most likely a must fix many of the problems in the existing javascript files. From command line, run:</p><pre>tsc -b -v</pre><p>… or if you prefer tsc to run incrementally and with a file watcher:</p><pre>tsc --build --verbose --incremental --watch</pre><pre># or shorter:</pre><pre>tsc -b -v -i -w</pre><p>Keep the compiler running in watch mode in a window as you resolve errors one by one.</p><h4>Order of fixing</h4><p>If possible, start with the “deepest” level of code, ie code loading data from disk/internet. Basically, if the LoadWeatherDataFromRemoteAPI() returns { Temparature: 25 } , the function should look somehting like this:</p><pre>function LoadWeatherDataFromRemoteAPI() : { Temparature: number } {<br> // ... code for fetching here <br>}</pre><p>This topic will be covered in more detail below (including how to handle Promise/await/async).</p><h4>An JsDoc opportunity</h4><p>The TypeScript transpiler understand JsDoc comments and vscode recognizes them, but once the conversion is complete some (much?) of the JsDoc isn’t needed. TypeScript should win for the types (and optionally keep JsDoc for other stuff)</p><p>If your code totally lacks JsDoc at this point, it <em>might </em>be helpful to write/generate it as an intermediate solution. It <em>will</em> help you resolve errors, but it’s also a step in the wrong direction. Once conversion is completed, this newly written JsDoc should probably be removed. JsDoc example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*-oj5COgxAr0DrsKwav6IFA.png" /></figure><p>And variables using /** @type { <em>thetype </em>} */</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*0SanGiXQofDGQpyB6yaazw.gif" /></figure><h4>Automatically writing the documentation / resolving the type</h4><p>Consider the following JavaScript code. The function lacks types on the parameter:</p><pre>function RandomNumber(iTo) {<br>    return Math.round(Math.random() * iTo + 0.5);<br>}</pre><p>It’s possible to automatcially infer the type :) But I strongly recommend to do this <em>after</em> the files has been renamed to .ts since it will write real typescript code (rather than jsDoc). Read more on this topic below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*x6dx0hBwBVl-6eP_EgAqnQ.gif" /></figure><h3>Resolving errors</h3><p>While keeping the files as .js, it’s possible to resolve a lot of problems. Now, if you already at this point decide to rename to .ts, it’s alright. Just read the section on renaming first :)</p><h4>Operator ‘xyz’ cannot be applied to types ‘string’ and ‘number’.</h4><p>Seems like an easy one, don’t mix types. :)</p><pre>// Incorrect type set<br>let a=&quot;0&quot;;<br>console.log(a+1);   // Disallowed, a is a string</pre><pre>// toFixed converts to string!<br>const a = 3.1415926;<br>const b = a.toFixed(2);<br>const c = 2 * b;     // Disallowed, b is a string</pre><h4>fs.readFileSync and JSON.parse problems</h4><pre>Argument of type &#39;Buffer&#39; is not assignable to parameter of type &#39;string&#39;.ts(2345)</pre><p>Solution:</p><pre># Change from:<br>let result1 = JSON.parse(fs.readFileSync(fileName));</pre><pre>To:<br>let result2 = JSON.parse(fs.readFileSync(fileName, &#39;utf-8&#39;));</pre><h4>If nothing else, just ignore the error</h4><p>Well, there might be errors that can be troublesome to fix right now. Just tag the line with @ts-ignore (and maybe add it to the backlog to fix it later):</p><pre>process.on(&#39;unhandledRejection&#39;, (error) =&gt; {<br>    //@ts-ignore<br>    logger.info(&quot;Unhandled exception - internal error. Stacktrace=&quot; + error.stack);<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kEvL6XPcPf3E4yNj9mAgQ.gif" /></figure><h3>Special notes about global variables and Express</h3><p>Not all projects include global variables or uses Express. This section is dedicated for problems related to that.</p><h4>declare global</h4><pre>error TS2339: Property ‘myVariable’ does not exist on type ‘Global &amp; typeof globalThis’.</pre><p>Solution: In a <strong>.d.ts</strong> file, define the object(s). Here’s some examples to get past this problem:</p><pre>var myVariable: boolean;<br>    var myClass1: Object;<br>    var myClass2: any;<br>    var myObject3: { Name: string, Username: string };<br>    var myObject3Array: { Name: string, Username: string }[];<br>}</pre><p>Typically you’d see the below style as recommendations, but above style will work with tsc, while running the code <em>and</em> with intellisense.</p><pre>declare global {<br>    namespace NodeJS {<br>        interface Global {<br>            myVariable: boolean,<br>            myClass1: Object,<br>            myClass2: any,<br>            myObject3: { Name: string, Username: string },<br>            myObject3Array: { Name: string, Username: string }[],<br>        }<br>    }<br>}</pre><p>Either way, use the one that works best for you.</p><h4>Express</h4><p>Add the types Express types as (don’t forget to import Express):</p><pre>import Express from &quot;express&quot;;</pre><pre>app.get(`/ping`, (req: <strong>Express.Request</strong>, res: <strong>Express.Response</strong>) =&gt; {<br>   return res.json({ result: &quot;pong&quot;});<br>});</pre><p>If you expect additional properties on for for example Express.Request , you might get an error as this:</p><pre>error TS2339: Property ‘User’ does not exist on type ‘Request&lt;ParamsDictionary&gt;’.</pre><p>Solution is to modify the global namespace (see above for another example).</p><pre>declare global {<br>  namespace Express {<br>    interface Request {<br>      User: { Name: string }<br>    }<br>  }<br>}</pre><h3>Try to run the project as-is</h3><p>If you manage do run tsc with zero errors, then there’s a chance the project <em>may</em> run at this time. Again, <em>transpiling </em>the code and <em>running </em>the code are two different things.</p><h4>From command line</h4><p>We’re going to avoid “compiling” (read: transpiling) into the /out/ destination directory using a build step, it’s better to setup all tools to run typescript as-is.</p><p>Running the code without transpiling is easy, it’s just to include ts-node in the start command:</p><pre># Faster startup<br>node.exe <strong>-r ts-node/register/transpile-only</strong> ./src/index.js</pre><pre># Or use:<br>node.exe <strong>-r ts-node/register</strong> ./src/index.js</pre><pre># Read more at: <a href="https://github.com/TypeStrong/ts-node">https://github.com/TypeStrong/ts-node</a></pre><p>Not getting a success? Want a working project? Check out the <a href="https://github.com/tomnil/emptyts">emptyts</a> project on github.</p><h4>Debugging directly from vscode</h4><p>Now, we haven’t configured vscode yet. You need to make additional changes for this to work. Open `launch.json` and use the follwing. Modify args to match the name of your starting file.</p><pre>{<br> // Detailed docs:<br> // <a href="https://code.visualstudio.com/docs/nodejs/nodejs-debugging">https://code.visualstudio.com/docs/nodejs/nodejs-debugging</a><br> &quot;version&quot;: &quot;0.2.0&quot;,<br> &quot;configurations&quot;: [<br><strong>  {<br>   &quot;name&quot;: &quot;Debug typescript&quot;,<br>   &quot;type&quot;: &quot;node&quot;,<br>   &quot;request&quot;: &quot;launch&quot;,<br>   &quot;smartStep&quot;: false,<br>   &quot;sourceMaps&quot;: true,<br>   &quot;args&quot;: [<br>    &quot;${workspaceRoot}/src/index.ts&quot;<br>   ],<br>   &quot;runtimeArgs&quot;: [<br>    &quot;-r&quot;,<br>    &quot;ts-node/register/transpile-only&quot;<br>   ],<br>   &quot;cwd&quot;: &quot;${workspaceRoot}&quot;,<br>   &quot;protocol&quot;: &quot;inspector&quot;,<br>   &quot;internalConsoleOptions&quot;: &quot;openOnSessionStart&quot;,<br>   &quot;env&quot;: {<br>    &quot;TS_NODE_FILES&quot;: &quot;true&quot; // Respect include/exclude in tsconfig.json =&gt; will read declaration files  (ts-node --files src\index.ts)<br>   },<br>   &quot;skipFiles&quot;: [<br>    &quot;&lt;node_internals&gt;/*&quot;,<br>    &quot;&lt;node_internals&gt;/**&quot;,<br>    &quot;&lt;node_internals&gt;/**/*&quot;,<br>    &quot;${workspaceRoot}/node_modules/**&quot;,<br>    &quot;${workspaceRoot}/node_modules/**/*&quot;<br>   ],<br>   &quot;outputCapture&quot;: &quot;std&quot;,<br>   &quot;stopOnEntry&quot;: false<br>  }</strong><br> ]<br>}</pre><p>Press `ctrl-shift-p` to bring up the command palette. Search and select for `Debug: Select and start debugging`. In the menu that appears, select `Debug typescript` (as named above).</p><p>Tip: Breakpoints is toggled by pressing F9 on a line.</p><h4>Nodemon? ts-node?</h4><p>If you want to run nodemon, check out the <a href="https://github.com/tomnil/emptyts">emptyts</a> project, it’s documented there.</p><h3>Changing require to import, and module.exports to export</h3><p>Exactly how to write import and export statements is somewhat outside of this guide, but it’s a good thing to mention. Also, this might not apply to your project.</p><p>Please understand: it’s not enough to fix only require, <em>both</em> require and exports needs to be done.</p><h4>Replacing “require” with “import”.</h4><p>Example:</p><pre>const stack = require(&#39;callsite&#39;);<br>const winston = require(&#39;winston&#39;);<br>const path = require(&quot;path&quot;);<br>require(&#39;winston-daily-rotate-file&#39;)</pre><p>will become:</p><pre>import stack from &#39;callsite&#39;;<br>import winston from &#39;winston&#39;;<br>import * as path from &#39;path&#39;;<br>import &#39;winston-daily-rotate-file&#39;;</pre><p><strong>Search and replace</strong></p><p>It’s not possible to make a successful search and replace, since import works slightly different.Begin with fixing some common requires like fs and path .</p><pre>Search: const fs = require(&quot;fs&quot;);<br>Replace: import * as fs from &#39;fs&#39;;</pre><pre>Search: const path = require(&quot;path&quot;);<br>Replace: import * as path from &#39;path&#39;;</pre><p>Since require does some magic behind the scenes, and import does not: it’s impossible to do make a straight search/replace from require to import. Depending on how the module is used any of the following could be used:</p><pre>// Entire module<br>import * as xyz from &#39;xyz&#39;;<br>import xyz from &#39;xyz&#39;;</pre><pre>// Specific object<br>import { User } from &#39;xyz&#39;;</pre><pre>// Both<br>import xyz, { User} from &#39;xyz&#39;;</pre><p>Now, this will most likely fail, but at least some manual writing can be avoided. Press `ctrl-shift-h`, and make sure you tick “regex”:</p><pre>Search: ^\w+\s+(\w+)\s+=\s+require\(([&quot;&#39;].*[&quot;&#39;])\);{0,2}$<br>Replace: import * as $1 from $2;</pre><p>Check the output of tsc and try to fix some of the obvious problems, but please be aware that <strong>it’s impossible to resolve all until export has been fixed as well.</strong> So keep on reading…</p><h4>Replacing “module.exports” with “export”</h4><p>Example:</p><pre>module.exports.Function1 = Function1;<br>module.exports.Function2 = Function2;<br>module.exports.Function3 = Function3;</pre><pre>// or:<br>module.exports = { Function1, Function2, Function3}</pre><p>becomes:</p><pre>export { Function1, Function2, Function3 }</pre><pre># Or use export before the function keyword:</pre><pre>export function CreateOrder() {<br>    // Do work<br>}</pre><pre># If you want a default export, use: </pre><pre>export default { Function1, Function2, Function3 }</pre><h4>Fixing “module.exports”</h4><p>Well, this is hard. There are no easy way of doing search &amp; replace on this one. A lot of manual fixing is needed. Try this:</p><pre>Search: (module\.exports\s=\s)(.*)$<br>Replace: export default $2</pre><p>Now fix the problems reported by tsc.</p><h4>Possible challenges with package.json</h4><p>It may help / make things worse if setting type to module .</p><pre>{<br>	&quot;name&quot;: &quot;my project1&quot;,<br>	&quot;version&quot;: &quot;1.0.0&quot;,<br>	&quot;private&quot;: true,<br>	&quot;type&quot;: &quot;module&quot;,<br>	 ...<br>}</pre><p>Not getting a success? Want a working project? Check out the <a href="https://github.com/tomnil/emptyts">emptyts</a> project on Github.</p><h3>Renaming all files .js to .ts</h3><p>Now, this is where it gets interesting. Renaming the files will disable some features and enable many others.</p><p>To rename all source files from .js to .ts, use a tool of your choice. Also change launch.json (and other places) from starting on index.js to index.ts</p><p><strong>IMPORTANT</strong>: Restart VSCode after the rename.</p><p>After the rename, every check of TypeScript will be activated. Probably both VSCode and tscwill report new errors. Some of these can easily be resolved while others may even require to redesign the code. Still, you can ask TypeScript to fallback to old javascript features — which probably is OK for many cases (simply by using // @ts-ignore). Turning a project into 100% TypeScript isn’t done in a heartbeat. :)</p><h4>Remove file extensions on import statements</h4><p>If you’ve referenced files with the full path including the extension, you may fail on <em>running</em> the code, but <em>not</em> on transpiling with tsc.</p><pre># Bad<br>import MeasureTime from &quot;./include/measuretime.js&quot;;</pre><pre># Good<br>import MeasureTime from &quot;./include/measuretime&quot;;</pre><p>Do a search/replace as:</p><pre>Search:   (import.*)[&#39;|&quot;](.*).js[&#39;|&quot;]<br>Replace:     $1 &#39;$2&#39;</pre><h4>Excluding folders from transpile</h4><p>If you have folders at the same level as `src` you may get this error:</p><pre>TS6059: File ‘abc’ is not under ‘rootDir’</pre><p>Exclude the folders by excluding folders in `tsconfig.json`, but make sure the TS_NODE_FILES is set (if its true, include/exclude will be used)</p><pre>&quot;include&quot;: [<br>	&quot;src/**/*.js&quot;,<br>	&quot;src/**/*.ts&quot;<br>],<br>&quot;exclude&quot;: [<br>	&quot;test&quot;,<br>	&quot;bin&quot;,<br>	&quot;out&quot;,<br>	&quot;additionalFolderToSkip&quot;<br>]</pre><h3>Inferring types (aka automatic documentation)</h3><p><strong>This part of the document contains the best tip :) </strong>Consider the following code. We can easy understand that the FindUser takes a parameter userID, and by looking at the code it’s both you and TypeScript understands its a string.</p><pre>const user = FindUser(&quot;John&quot;);<br>if (user)<br>    console.log(`User found. Name=${user.Name}`);</pre><pre>function FindUser(userID) {     // No type on param or return</pre><pre>    if (userID === &quot;John&quot;)<br>       return { Name: &quot;John&quot;, Age: 99 };<br>    else<br>        return undefined;<br>}</pre><p>.. but it would be better if it looked like this:</p><pre>function FindUser(userID<strong>: string</strong>)<strong> : { Name: string, Age: number } | undefined</strong> {     // We&#39;re clear on expectations!</pre><pre>    ... code follows</pre><pre>}</pre><p>Either write this by hand, <strong>or use the following tricks</strong>:</p><p>To infer the parameters, click <strong>a parameter</strong> and allow the yellow suggestion appear “Infer parameter from usage”. This will examine the code determinate what the parameter’s type is. Sometimes the result isn’t right, so check that it makes sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*luVeLx9NueZXwB0odlesUg.gif" /></figure><p>Now return parameters can <em>also</em> be inferred. Set the cursor the cursor needs to be at <strong>the name of the function</strong> and press ctrl + shift + r. Optionally use the command palette and search for “Refactor…”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*spATDXT5mCkBBIU0BLAVVg.gif" /></figure><p>One final tip is to use this style for return parameters. This way of structuring the code ensures the type is only written once.</p><pre>function FindUser(userID: string): typeof result {</pre><pre>  let result: { Name: string, Age: number } | undefined = undefined;</pre><pre>  if (userID === &quot;John&quot;)<br>    result = { Name: &quot;John&quot;, Age: 99 };</pre><pre>  return result;</pre><pre>}</pre><p>Alternatively use this style, but methods returning a Promise will be challenging:</p><pre>function FindUser(userID: string): { Name: string, Age: number } | undefined {</pre><pre>    let result: ReturnType&lt;typeof FindUser&gt; = undefined;</pre><pre>    if (userID === &quot;John&quot;)<br>        result = { Name: &quot;John&quot;, Age: 99 };</pre><pre>    return result;</pre><pre>}</pre><h3>Resolving errors in .ts-files</h3><h4>Object is possibly ‘undefined’</h4><p>Since the tsconfig.json specifies strickNullChecks: true , then TypeScript will give errors for all code that hasn’t specifically checked for undefined. This results in the following error:</p><pre>TS2532: Object is possibly &#39;undefined&#39;.</pre><p>As an example: The sought user may not be found and user.SendResetPasswordLink() will therefore fail.</p><pre># Bad code<br>let user = userlist.find(&quot;admin&quot;);<br>user.SendResetPasswordLink();  // No check if user is undefined</pre><pre># Correct code:<br>let user = userlist.find(&quot;admin&quot;);<br>if (user)<br>   user.SendResetPasswordLink();</pre><h4>Function arguments</h4><p>All arguments must be used or specified as optional.</p><pre>TS2554: Expected 2 arguments, but got 1.</pre><p>Example:</p><pre>let user = FindUser(&quot;admin&quot;);<br>function FindUser(userName: string, region: string) {<br>    // ... implementation here<br>}</pre><p>Solution is either to call with both parameters, make region optional or have a default:</p><pre>function FindUser(userName: string, region?: string) {<br>    // ... region can now be a string | undefined.<br>}</pre><pre>function FindUser(userName: string, region= &quot;Europe&quot;) {<br>    // ... region can now be a string <br>}</pre><h4>async function and the keyword Promise</h4><p>If you write an async function, the return value of the function must be a Promise. Consider this function:</p><pre>function UserExists(userID: string): boolean {<br>    return (userID === &quot;John&quot;);<br>}</pre><p>If it needs to be async, then the return parameter will change from boolean to Promise&lt;boolean&gt; .</p><pre><strong>async </strong>function UserExists(userID: string): <strong>Promise&lt;boolean&gt;</strong> {<br>    // Additional code here requiring it to be async.. :)<br>    return (userID === &quot;John&quot;);<br>}</pre><h4>Aren’t many objects “any” now?</h4><p>Well, yes. let a; is basically equal to let a : any;</p><p>This means you can do whatever you like with the object (as in JavaScript), but that’s not what we really want with going TypeScript. We want control and <em>knowing</em> what we’re working with.</p><p>If you want to disable the use of any, then open tsconfig.json and change noImplicitAny from false to true and enjoy the errors :)</p><h4>Using {} in TypeScript.</h4><p>This may be working in JavaScript, but is annoying in TypeScript. A variable will in be declared as just {} , and nothing more. Example:</p><pre>let myBox = {};<br>myBox.contents = &quot;fruit&quot;;<br># ^^^ Will render &quot;TS2339: Property &#39;contents&#39; does not exist on type &#39;{}&#39;.&quot;</pre><p>If you absolutely want to use {}, then you can resolve this issue atleast three different ways:</p><pre># Set the type (Works since contents is optional)<br>let myBox1: { contents?: string } = {};<br>myBox1.contents = &quot;fruit&quot;;</pre><pre># Better<br>let myBox2: { contents: string };   // Variable is unused<br>myBox2 = { contents: &quot;fruit&quot; };</pre><pre># Or in this case, best (the type for myBox3 is inferred automatically)<br>let myBox3 = { contents: &quot;fruit&quot; };</pre><pre># Basically turn of type checking (not recommended)<br>let myBox4 : any = {};<br>myBox4.contents = &quot;fruit&quot;;</pre><h4>Type ‘xyz’ is not assignable to type ‘never’ (part 1)</h4><p>Doing for example .push on arrays that has been defined within an object will give this error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izbc_2VIPKSNhHEAP0hl-w.png" /></figure><p>Another simpler example:</p><pre>let users = [];<br>users.push(&quot;John&quot;);</pre><p>will result in:</p><pre>TS2345: Argument of type &#39;string&#39; is not assignable to parameter of type &#39;never&#39;.</pre><p>The solution is to specify the type:</p><pre>let users<strong>: string[</strong>] = [];<br>users.push(&quot;John&quot;);</pre><p>If the type is unknown at the time of doing the fix, do:</p><pre>let users: any[] = [];</pre><pre>// or, if possible, use unknown. It&#39;s a stronger type</pre><pre>let result : unknown[] = [];</pre><h4>Type ‘xyz’ is not assignable to type ‘never’.. (part 2)</h4><p>For objects with arrays, there are atleast three different solutions to this problem.</p><pre>const payload = {<br>    name: &quot;Tomas&quot;,<br>    accessrights: []       // Will become &quot;never[]&quot;<br>};</pre><pre>payload.accessrights.push(&quot;Admin&quot;); </pre><pre>// Error: &quot;Argument of type &#39;string&#39; is not assignable to parameter of type &#39;never&#39;.&quot;</pre><p><strong>Solution 1 — Inline types</strong></p><pre>const payload:<strong> {<br>    name: string,<br>    accessrights: string[]<br>} </strong>= {<br>    name: &quot;Tomas&quot;,<br>    accessrights: []<br>};</pre><p><strong>Solution 2— Define a type (or interface)</strong></p><pre><strong>type ThePayload = { name: string, accessrights: string[] }<br></strong>// interface IThePayload { name: string, accessrights: string[] }</pre><pre>const payload<strong>: ThePayload</strong> = {<br>    name: &quot;Tomas&quot;,<br>    accessrights: []<br>};</pre><p><strong>Solution 3— type inference</strong></p><p>This one is the fastest implementation, but it gives less readable code:</p><pre>const payload: ThePayload = {<br>    name: &quot;Tomas&quot;,<br>    accessrights: <strong>&lt;string[]&gt;</strong>[]<br>};</pre><h4>Dates and milliseconds</h4><p>You cannot do operations like this:</p><pre>let t1 = new Date();<br>let t2 = new Date();<br>console.log(t2 - t1);</pre><p>With TypeScript you need to be precise and specific:</p><pre>let t1 = new Date().getTime();<br>let t2 = new Date().getTime();<br>console.log(t2 - t1);</pre><h4>Types differ / TypeScript is smart</h4><p>Consider the following code. a is a string, and b can be a string <em>or</em> undefined. How can the assignment on line 3 occour?</p><pre>let a: string;<br>const b: string | undefined = &quot;Banana&quot;;<br>a = b;</pre><p>Well, TypeScript is smart. It undestands that b is a string. Hovering over b gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*uKiV8YnMTppDPbu2E4l_fg.gif" /></figure><p>If statements is the best way to visualize this. Foo can clearly be a string or undefined, but after the if-statement it can only be a string:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*wUSSj7tbR3gWBGkQTAepwA.gif" /></figure><h3>How strict should the destination code be?</h3><p>Well, that’s a matter of opinion. The following settings controll most of the strictness:</p><h4>tsconfig.json — strictNullChecks</h4><p>With this setting on all code needs to handle undefined properly.</p><pre>function GetTemparature(): <strong>number | undefined</strong> {<br>    // A piece of code should return the temparature,<br>    // but that occasionally returns undefined<br>}</pre><pre>const temp = GetTemparature();<br>if (temp &gt; 50)  <strong>// Error, temp may be undefined</strong><br>    console.log(&quot;It&#39;s hot.&quot;);</pre><h4>tsconfig.json — useUnknownInCatchVariables</h4><p>If this setting is on, the variable used in catch must be handled properly:</p><p><strong>Bad code:</strong></p><pre>try {<br>   // Some bad code that generates an exception<br>} catch (error) {<br>   console.log(error.message);  // Fail!</pre><p><strong>Good code:</strong></p><pre>try {<br>   // Some bad code that generates an exception<br>} catch (error) {<br><strong>   if (error instanceof Error)<br>       </strong>console.log(error.message);  // OK!<br>}</pre><h4>tsconfig.json — noImplicitAny</h4><p>When set to true, it’s not allowed to use any :</p><pre>const user: <strong>any </strong>= { name: &quot;Tomas&quot;, Foo: &quot;Bar&quot; };</pre><h4>// @ts-ignore</h4><p>Even if all the above settings are turned on, it’s still possible to just ignore the errors. A completely converted code base should strive for having none to very few // @ts-ignore .</p><p>Of course, there are more tricks to converting, but I hope this guide will give you some hints.</p><p><strong>Enjoy </strong>:)</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e7d031a8f49" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-convert-node-js-code-from-javascript-to-typescript-8e7d031a8f49">How to Convert Node.js Code from JavaScript to TypeScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Write an NPM Package Without Publishing to Git/NPM]]></title>
            <link>https://javascript.plainenglish.io/how-to-write-an-npm-package-without-publishing-to-git-npm-68068caf466f?source=rss-fffaf8ff7bac------2</link>
            <guid isPermaLink="false">https://medium.com/p/68068caf466f</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tomas Nilsson]]></dc:creator>
            <pubDate>Tue, 07 Sep 2021 08:58:17 GMT</pubDate>
            <atom:updated>2021-09-07T08:58:17.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8fB3mbo0lxl4KO_L" /><figcaption>Photo by <a href="https://unsplash.com/@pinjasaur?utm_source=medium&amp;utm_medium=referral">Paul Esch-Laurent</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Want to write an npm package without publishing to npm or git? And be able to use it in a project? Well, keep reading!</p><p>NPM is fantastic, but it can be somewhat challenging if you just want to do some prototyping or just test out stuff. This guide shows how to manually write a package and still be able to test/use it in a project. For this to work, two instances of VSCode are needed. One for the package, and one for the project that references the package.</p><p>foopackage: This is the package to write (i.e., something that eventually will end up at the npm repository).</p><p>demo1 : This is the project that references foopackage .</p><h3>Setup “demo1”</h3><p>Just create the project as normal, if nothing else clone <a href="https://github.com/tomnil/emptyts">emptyts</a>:</p><pre>git clone <a href="https://github.com/tomnil/emptyts">https://github.com/tomnil/emptyts</a><br>ren emptyts demo1<br>cd demo1<br>npm install</pre><h4>Placeholder in node_modules</h4><p>It’s time to create a placeholder for foo inside the node_modules of demo1.</p><pre>cd node_modules<br>mkdir foopackage<br>cd foopackage</pre><p>Next, add this file with the name package.json in the root of the folder:</p><pre>{<br>  &quot;name&quot;: &quot;foopackage&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;bar&quot;,<br>  &quot;main&quot;: &quot;./bin/index.js&quot;<br>}</pre><h3>Setup “foopackage”</h3><p>Just create the solution as normal, if nothing else clone <a href="https://github.com/tomnil/emptyts">emptyts</a> (again):</p><pre>git clone <a href="https://github.com/tomnil/emptyts">https://github.com/tomnil/emptyts</a><br>ren emptyts foopackage<br>cd foopackage<br>npm install</pre><p>Write some interesting (exported) code in index.ts :</p><pre>export function CheckIsFoo(data: string) : boolean {<br>    return (data===&quot;foo&quot;);<br>}</pre><p>Open tsconfig.json and modify the outdir to reflect the (relative) target path. The outDir should point to the node_modules of the <strong>demo1</strong> project.</p><p>At the same time, make sure to emit declarations, without this the error<em>` Cannot find module ‘foopackage’ or its corresponding type declarations`</em> will occur.</p><pre>&quot;compilerOptions&quot;: {</pre><pre>    &quot;outDir&quot;: &quot;../demo1/node_modules/foopackage/bin&quot;,<br>    &quot;declaration&quot;: true</pre><pre>}</pre><p>Compile:</p><pre>tsc -b -w</pre><p>Check the node_modules folder, if done right the bin -folder is created and inside there will be an index.js (and index.d.ts)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*JbEKcXilp0yWshKx7X0X4A.png" /></figure><h4>Automatically updating..</h4><p>Setup tsc to recompile automatically on changes (from your foopackage folder into <strong>demo1:s</strong><em> </em>node_modules) by running this:</p><pre>tsc -b -v -w -i</pre><h3>Referencing “foopackage” from “demo1”</h3><p>Alright, the result of the foopackage is placed inside node_modules . Go back to the demo1 solution and open package.json . Next, add the line &quot;foopackage&quot;: &quot;*&quot; under dependencies :</p><pre>&quot;dependencies&quot;: {<br><strong>    &quot;foopackage&quot;: &quot;*&quot;<br></strong>  }</pre><p>If all is good now, the package can successfully be referenced as:</p><pre>import { CheckIsFoo } from &#39;foopackage&#39;;</pre><pre>console.log(CheckIsFoo(&quot;Bar&quot;));  // Returns false</pre><h3>Publishing to NPM…</h3><p>If you decide to publish to npm, there’s a guide to follow: <a href="https://docs.npmjs.com/creating-and-publishing-scoped-public-packages">https://docs.npmjs.com/creating-and-publishing-scoped-public-packages</a></p><p>Basically, the short version is:</p><ul><li>Modify tsconfig.json to emit output files into a local bin (rather than the relative path to node_modules)</li><li>Create aLICENSEand README.md -file.</li><li>Update package.json with all the details like author, license, keywords, and others.</li><li>Push your code to GitHub (or similar) and update package.json with information on the repo and bugs.</li></ul><pre>&quot;repository&quot;: {<br>    &quot;type&quot;: &quot;git&quot;,<br>    &quot;url&quot;: &quot;git+<a href="https://github.com/tomnil/runtime-typescript-checker.git">https://github.com/</a>name/xyz.git&quot;<br>  },<br>  &quot;bugs&quot;: {<br>    &quot;url&quot;: &quot;<a href="https://github.com/tomnil/runtime-typescript-checker/issues">https://github.com/</a>name<a href="https://github.com/tomnil/runtime-typescript-checker/issues">/xyz/issues</a>&quot;<br>  }</pre><ul><li>Log in to npm (create an account if needed)</li><li>Run npm publish --access public</li></ul><p>To delete it use npm unpublish &lt;packagename&gt; -f . Read more <a href="https://docs.npmjs.com/unpublishing-packages-from-the-registry">https://docs.npmjs.com/unpublishing-packages-from-the-registry</a></p><h3>Enjoy</h3><p>/T</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68068caf466f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-write-an-npm-package-without-publishing-to-git-npm-68068caf466f">How to Write an NPM Package Without Publishing to Git/NPM</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Automatically Convert TypeScript Types to Runtime Validators]]></title>
            <link>https://javascript.plainenglish.io/how-to-automatically-convert-typescript-types-to-runtime-validators-5b06ee269b13?source=rss-fffaf8ff7bac------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b06ee269b13</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Tomas Nilsson]]></dc:creator>
            <pubDate>Mon, 23 Aug 2021 08:02:40 GMT</pubDate>
            <atom:updated>2021-08-23T08:02:40.057Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article will show how to generate runtime validators from TypeScript files.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nRU66YQEmjfLtr9D" /><figcaption>Photo by <a href="https://unsplash.com/@baciutudor?utm_source=medium&amp;utm_medium=referral">Tudor Baciu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a developer, it’s probably a good thing to be lazy. If some code has been written once (like TypeScript definitions), why write similar code that does the same thing again? It’s error-prone and takes a lot of time. What if there was a way to convert those Types, Enums and Interfaces into some kind of runtime code? Well, there is.</p><p>This article demonstrates the package runtime-typescript-checker , which can be found at <a href="https://www.npmjs.com/package/runtime-typescript-checker">https://www.npmjs.com/package/runtime-typescript-checker</a>.</p><h3>TL;DR</h3><p>This article explains how to automatically generate functions IsUserTypeGuard() and ValidateUser() from:</p><pre>export interface User {<br>  Name: string;<br>  HasPaid: &quot;Yes&quot; | &quot;No&quot;,<br>  Notes?: string<br>}</pre><h3>Build</h3><p>First the runtime-typescript-checker will parse the source code (TypeScript files containing exported Types, Enums and Interfaces).</p><p>At the end of the parse, new files will be created (or updated) which can be used.</p><h4>Example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*8IC-6EoO197VyqLnRxDf3w.png" /></figure><p>Will generate a file with two functions for each exported type. One TypeGuard and one Validator-function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*iR9fzGwOwy22MnVk6qBPGw.png" /></figure><h3>Using the tests in runtime (TypeGuard)</h3><p>A few lines of code are required to initialize the runtime checker, but after that has been completed, it’s only to use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*BOU2zktbsPguqtZ4vondMQ.png" /></figure><h3>Using the tests in runtime (Validate)</h3><p>TypeGuards are great, but often there’s a need for the details about the errors. As said before, there is also a validator function which clearly presents the errors found in the payload:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*NARFf5yLUySIxDj8AWF4Pg.png" /></figure><p>So given the above interfaces, this payload:</p><pre>{<br>   Name: &quot;Tomas&quot;,<br>   HasPaid: &quot;Maybe&quot;,<br>   Role: dances.eRole.Leader,<br>   DanceClass: {<br>       ID: &quot;7&quot;,<br>       Name: &quot;Lindy Hop Autumn&quot;,<br>       Level: &quot;?&quot;,<br>   },<br>   Notes: undefined,<br>   MemberShip: true<br>}</pre><p>Would render the following errors:</p><pre>[<br>    {<br>        &quot;instancePath&quot;: &quot;/HasPaid&quot;,<br>        &quot;schemaPath&quot;: &quot;#/properties/HasPaid/enum&quot;,<br>        &quot;keyword&quot;: &quot;enum&quot;,<br>        &quot;params&quot;: {<br>            &quot;allowedValues&quot;: [<br>                &quot;No&quot;,<br>                &quot;Yes&quot;<br>            ]<br>        },<br>        &quot;message&quot;: &quot;must be equal to one of the allowed values&quot;<br>    },<br>    {<br>        &quot;instancePath&quot;: &quot;/DanceClass/Level&quot;,<br>        &quot;schemaPath&quot;: &quot;#/properties/DanceClass/properties/Level/enum&quot;,<br>        &quot;keyword&quot;: &quot;enum&quot;,<br>        &quot;params&quot;: {<br>            &quot;allowedValues&quot;: [<br>                &quot;A&quot;,<br>                &quot;B&quot;,<br>                &quot;C&quot;,<br>                &quot;D&quot;,<br>                &quot;E&quot;<br>            ]<br>        },<br>        &quot;message&quot;: &quot;must be equal to one of the allowed values&quot;<br>    }<br>]</pre><h3>Demo?</h3><pre>git clone <a href="https://github.com/tomnil/runtime-typescript-checker-demo">https://github.com/tomnil/runtime-typescript-checker-demo</a><br>cd runtime-typescript-checker-demo<br>npm install</pre><pre># And then one of the following:</pre><pre>npm run build-example1<br>npm run build-example1-force</pre><pre>npm run test-example1</pre><p>There’s more information on the <a href="https://github.com/tomnil/runtime-typescript-checker-demo">Demo project page</a>.</p><h4>Enjoy</h4><p>:)</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b06ee269b13" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-automatically-convert-typescript-types-to-runtime-validators-5b06ee269b13">How to Automatically Convert TypeScript Types to Runtime Validators</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript and Global Variables in Node.js]]></title>
            <link>https://javascript.plainenglish.io/typescript-and-global-variables-in-node-js-59c4bf40cb31?source=rss-fffaf8ff7bac------2</link>
            <guid isPermaLink="false">https://medium.com/p/59c4bf40cb31</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Tomas Nilsson]]></dc:creator>
            <pubDate>Mon, 16 Aug 2021 05:57:56 GMT</pubDate>
            <atom:updated>2021-08-16T13:04:18.760Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to make global variables in Node.js using TypeScript <em>and</em> make sure the types are correct.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vYI4K5VRGLhWo9RJ" /><figcaption>Photo by <a href="https://unsplash.com/@blakeconnally?utm_source=medium&amp;utm_medium=referral">Blake Connally</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Prerequisites:</strong> VSCode and TypeScript should be already installed.</p><p><strong>TL;DR</strong> — Here is a working project: <a href="https://github.com/tomnil/emptyts">emptyts</a>.</p><h3>Declaring global variables</h3><p>Create a file in the root of the project named global.d.ts with the following content. Please note:</p><ul><li>The use of var , it’s required for this to work (see <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#type-checking-for-globalthis">typescriptlang.org</a> for information about this).</li><li>Without the export {} , all variables will become any</li></ul><pre>declare global {</pre><pre>    var Config: {<br>        Foo: string;<br>    };</pre><pre>    var Foo: string;<br>}</pre><pre>export { };</pre><p>In the index.ts file, try to use the variables:</p><pre>global.Config = { Foo: &quot;Bar&quot; };</pre><pre>global.Foo = &quot;Bar&quot;;</pre><h3>Compiling with TypeScript</h3><p>Make sure the tsconfig.json has proper sections for include and exclude . Example follows:</p><pre>&quot;include&quot;: [<br>    &quot;src/**/*.ts&quot;,<br>  ],<br>  &quot;exclude&quot;: [<br>    &quot;node_modules&quot;,<br>    &quot;&lt;node_internals&gt;/**&quot;,<br>    &quot;bin/**&quot;<br>  ]</pre><p>Next, just compile (from the terminal). All should be OK.</p><pre>tsc -b -v</pre><h3>Running from the terminal</h3><pre>node -r ts-node/register/transpile-only src\index.ts</pre><h3>Running in VSCode</h3><p>Use this launch.json (or copy the configuration). Press F5 alternatively select and start the Debug typescript configuration by bringing up the command palette (ctrl-shift-p) and search for “Select and start debugging”.</p><pre>{<br> // Detailed docs:<br> // <a href="https://code.visualstudio.com/docs/nodejs/nodejs-debugging">https://code.visualstudio.com/docs/nodejs/nodejs-debugging</a><br> &quot;version&quot;: &quot;0.2.0&quot;,<br> &quot;configurations&quot;: [<br>  {<br>   &quot;name&quot;: &quot;Debug typescript&quot;,<br>   &quot;type&quot;: &quot;node&quot;,<br>   &quot;request&quot;: &quot;launch&quot;,<br>   &quot;smartStep&quot;: false,<br>   &quot;sourceMaps&quot;: true,<br>   &quot;args&quot;: [<br>    &quot;${workspaceRoot}/src/index.ts&quot;<br>   ],<br>   &quot;runtimeArgs&quot;: [<br>   &quot;-r&quot;,<br>    &quot;ts-node/register/transpile-only&quot;<br>   ],<br>   &quot;cwd&quot;: &quot;${workspaceRoot}&quot;,<br>   &quot;protocol&quot;: &quot;inspector&quot;,<br>   &quot;internalConsoleOptions&quot;: &quot;openOnSessionStart&quot;,<br>   &quot;env&quot;: {<br>    &quot;TS_NODE_FILES&quot;: &quot;true&quot; // Respect include/exclude in tsconfig.json =&gt; will read declaration files  (ts-node --files src\index.ts)<br>   },<br>   &quot;skipFiles&quot;: [<br>    &quot;&lt;node_internals&gt;/*&quot;,<br>    &quot;&lt;node_internals&gt;/**&quot;,<br>    &quot;&lt;node_internals&gt;/**/*&quot;,<br>    &quot;${workspaceRoot}/node_modules/**&quot;,<br>    &quot;${workspaceRoot}/node_modules/**/*&quot;<br>   ],<br>   &quot;outputCapture&quot;: &quot;std&quot;,<br>   &quot;stopOnEntry&quot;: false<br>  }<br> ]<br>}</pre><h3>Initializing global variables</h3><p>In the following piece of code, we will set up a global logger and initialize it. Again, the variables <em>must</em> use var in order to work.</p><h4>global.d.ts</h4><pre>type Logger = {<br>    Info: (iMessage: string) =&gt; void<br>}</pre><pre>declare global {<br>    var Foo: string;<br>    var log: Logger;<br>}</pre><pre>export { };</pre><h4>index.ts</h4><p>index.ts initializes the global logger and then begins to use it.</p><p>Note that <em>initializing </em>the variable requires the use of global. (or globalThis. ), but <em>using it doesn’t</em>. Example:</p><pre>import * as Logger from &#39;./logger&#39;;<br>import * as expresshelper from &#39;./expresshelper&#39;</pre><pre><strong>global.log </strong>= Logger;</pre><pre><strong>log.Info</strong>(&quot;Booting system...&quot;);<br>global.Foo = &quot;Bar&quot;;<br>expresshelper.Init();<br>log.Info(&quot;Booting system Complete!&quot;);</pre><pre>export { }</pre><h4>logger.ts</h4><p>The fantastic logger :)</p><pre>console.log(&quot;logger is initializing...&quot;);</pre><pre>export function Info(iMessage: string) {<br>    console.log(`${new Date().toISOString()} Saving to log: ${iMessage}`);<br>}</pre><h4>expresshelper.ts</h4><p>Note the // log.info , it will be discussed below.</p><pre>// log.Info(&quot;Setting up Express&quot;);</pre><pre>export function Init() {<br>    log.Info(&quot;Initializing Express.&quot;)<br>}</pre><h4>Starting this code...</h4><p>If you run this code, the following output will be rendered (as expected).</p><pre>logger is initializing...<br>2021-08-14T08:51:25.620Z Saving to log: Booting system...<br>2021-08-14T08:51:25.621Z Saving to log: Initializing Express.<br>2021-08-14T08:51:25.621Z Saving to log: Booting system Complete!</pre><h4>Importing and code defined at the root of a file</h4><p>What&#39;s important to understand is that import runs the code at <em>the point of the file is read</em>, so trying to uncomment the use of log.info in the expresshelper.ts file will give this error (since the global variable log is used before it has been initialized in index.ts ).</p><pre>log.Info(&quot;Setting up Express&quot;);<br>^<br>ReferenceError: log is not defined</pre><p>So, avoid code that uses global variables at the root of the files. Or avoid it altogether. :)</p><h3>Modifying the global variables for another module</h3><p>Example for Express follows:</p><h4>global.d.ts</h4><pre>import &quot;express&quot;;</pre><pre>declare global {<br>    namespace Express {<br>        interface Request {<br>            token: string,<br>            UserID: string<br>        }<br>    }<br>}</pre><pre>export { };</pre><h3>Enjoy! :)</h3><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59c4bf40cb31" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/typescript-and-global-variables-in-node-js-59c4bf40cb31">TypeScript and Global Variables in Node.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Guide to Kickstarting Backend TypeScript Development]]></title>
            <link>https://javascript.plainenglish.io/the-guide-to-kickstarting-backend-typescript-development-e2656c2f5d17?source=rss-fffaf8ff7bac------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2656c2f5d17</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tomas Nilsson]]></dc:creator>
            <pubDate>Tue, 08 Jun 2021 19:54:27 GMT</pubDate>
            <atom:updated>2021-08-30T21:13:30.798Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*igDm8VkbIbAH938I" /><figcaption>Photo by <a href="https://unsplash.com/@oskaryil?utm_source=medium&amp;utm_medium=referral">Oskar Yildiz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article requires you to have at least some TypeScript knowledge. Topics like ReturnType, Partial, Generics &lt;T&gt; , intersections, how to modify the global namespace, and the tsc command line will be covered. All the while focusing on using the type of safety that TypeScript offers.</p><p>Let’s begin with establishing a baseline on a couple of things.</p><h3>Running vs developing</h3><p>This statement is something I’d wished someone had been more specific on when starting to learn TypeScript. <em>Writing </em>the code and <em>running </em>the code is two very different things. TypeScript <em>only</em> exists while developing and what’s <em>really </em>running is plain JavaScript. This makes debugging harder and using types while in runtime is impossible (except for the ones supported by vanilla JavaScript).</p><h3>tsconfig.json recommendations</h3><p>Keep the settings as tight as possible and let TypeScript shine. This <em>especially </em>includes noImplicitAny: true and strictNullChecks: true . Keeping the settings tight seem annoying at times, but for the long run — they’re a winning concept. Fewer bugs, better IntelliSense, and refactoring becomes a walk in the park.</p><h4>Target</h4><p>There is a number of variations on target , se documentation at <a href="https://www.typescriptlang.org/tsconfig/#target">https://www.typescriptlang.org/tsconfig/#target</a>. For backend development, there’s no need to consider browser compatibility. Just use the latest and greatest features.</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ES2020&quot;, <br>    &quot;module&quot;: &quot;commonjs&quot;, /*  &#39;commonjs&#39;, &#39;es2020&#39;, or &#39;ESNext&#39;.  */<br>    &quot;outDir&quot;: &quot;./out&quot;,<br>    &quot;rootDir&quot;: &quot;./src&quot;, <br>    &quot;strict&quot;: true, <br>    &quot;esModuleInterop&quot;: false,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;forceConsistentCasingInFileNames&quot;: true, <br>    &quot;allowUnreachableCode&quot;: true,<br>   <strong> &quot;noImplicitAny&quot;: true,<br>    &quot;strictNullChecks&quot;: true,</strong><br>    &quot;strictPropertyInitialization&quot;: true,<br>    &quot;alwaysStrict&quot;: true,<br>    &quot;noImplicitThis&quot;: true,<br>    &quot;strictBindCallApply&quot;: true,<br>    &quot;experimentalDecorators&quot;: true,<br>    &quot;incremental&quot;: true,<br>    &quot;noUncheckedIndexedAccess&quot;: true<br>  }<br>}</pre><h3>Defining a simple type</h3><p>Before diving in to the interesting details, let&#39;s just take a brief look at how to define a simple type:</p><pre>type User = {<br>    Name: string,<br>    AccessLevel: &quot;NewUser&quot; | &quot;User&quot; | &quot;Admin&quot;<br>}</pre><p>To use it, just reference the type with name Useras in this code:</p><pre>function Login(userName: string, pw: string) : User | undefined {</pre><pre>    let theUser: User | undefined = undefined;</pre><pre>    if (userName === &quot;root&quot; &amp;&amp; pw=== &quot;root&quot;)<br>        theUser = { Name: &quot;Root&quot;, AccessLevel: &quot;Admin&quot; };</pre><pre>     return theUser;<br>}</pre><p>Alright, with that out of the way, let’s jump into business.</p><h3>Known type vs “any” vs “unknown”</h3><h4>any</h4><p>Objects that are defined as any can be considered to be a “JavaScript object”. In essence, all operations are allowed and unchecked (assigning values, deleting values, and others). Consider it to be the programmer&#39;s decision to say “I don’t know anything about this variable, and it’s ok to access, delete and modify any values on it without any type checking”.</p><p>any is really useful when migrating from JavaScript to TypeScript, but try to stay clear of it. If there’s a must for it, change tsconfig.json , setting noImplicitAny to false to decrease the number of errors.</p><pre>let a: <strong>any </strong>= {<br>    Foo: &quot;1&quot;<br>};</pre><pre>a = { Foo: &quot;100&quot;, Fruit: &quot;Banana&quot; };   // No problem</pre><pre>a.Bar = &quot;2&quot;;         // No problem<br>delete a.Foo;        // No problem</pre><pre>console.log(a.Foo);  // Returns undefined</pre><h4>unknown</h4><p>The unknown type is somewhat different. It’s possible to assign whatever you like (as with any), but trying to access/modify the values gives an error.</p><pre>let a: <strong>unknown </strong>= {<br>    Foo: &quot;1&quot;<br>};</pre><pre>a = { Foo: &quot;100&quot;, Fruit: &quot;Banana&quot; };   // No problem</pre><pre>a.Bar = &quot;2&quot;;         // Returns error<br>delete a.Foo;        // Returns error</pre><pre>console.log(a.Foo);  // Returns error</pre><h4>never</h4><p>never doesn’t appear in good written TypeScript, but it might when converting from JavaScript to TypeScript. Consider the following scenairo:</p><pre>const Order = {<br>    OrderID: &quot;1234&quot;,<br>    OrderRows: []<br>};</pre><pre>Order.OrderRows.push({ ArticleID: 123 });</pre><p>Since there are no types defined on the Order object, TypeScript will try to figure out how the object looks like. Unfortunately, the OrderRows is just an array, but the type for it cannot be determinated. Because of this, the type will be set to never .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*RkNGwWSWdl8KtViFHg3XCQ.png" /></figure><p>Resolving the issue is easy, just specify the type of the object:</p><pre>const Order : { OrderID: string, OrderRows: {ArticleID: number}[] }= {<br>    OrderID: &quot;1234&quot;,<br>    OrderRows: []<br>};</pre><pre>Order.OrderRows.push({ ArticleID: 123 });</pre><h3>Getting to the type…</h3><p>Now in theory all objects are well defined and the type is known. In practice, most (all?) objects which are loaded from disk or fetched remotely are not. As a developer, this brings a challenge as (for example) a get request to fetch data returns an object of some kind that needs to be adapted to TypeScript.</p><p>There are (at least) four methods to assign a type to an object:</p><h4>Method 1: Type assertions (or casting if you prefer c# syntax)</h4><pre>const myObject = <strong>&lt;TheTargetType&gt;</strong>request(&quot;http://...&quot;);</pre><pre>// or</pre><pre>const myObject = request(&quot;http://...&quot;) <strong>as TheTargetType</strong></pre><h4>Method 2: Declare a variable with a specific type</h4><pre>const myObject : <strong>TheTargetType </strong>= request(&quot;http://...&quot;);</pre><h4>Method 3: Use User Defined Type Guards</h4><p>User-Defined Type Guards are functions that examine an object, and if it passes set requirements, it’s considered to be of a certain type.</p><pre>// The type<br>type Person = { Name: string, Age: string }</pre><pre>// User Defined Type Guard<br>function isPerson(object: unknown): <strong><em>object is Person</em></strong> {<br>    // Rules: Name and Age must exist in in the object.<br>    const keys = Object.keys(data);<br>    return ([&quot;Name&quot;, &quot;Age&quot;].every(v =&gt; keys.includes(v)));<br>}</pre><pre>// The unknown data (gotten from somewhere)<br>const rawData = `{&quot;Name&quot;:&quot;Sarah&quot;,&quot;Age&quot;:30}`;<br>const data = JSON.parse(rawData);         // type is &quot;any&quot;</pre><pre>// Using the type guard<br>if (isPerson(data)) {<br>    // data is of type Person (inside this closure)<br>    console.log(`name: ${data.Name}, age ${data.Age}`);<br>}</pre><h4>Method 4: Generics</h4><p>Generics especially useful when loading remote data from for example a website. Since generics are so powerful, there’s a dedicated chapter to it below.</p><pre>async function FetchRemoteSite&lt;T&gt;(url: string): Promise&lt;T&gt; {<br>  const result = await axios.get(`<a href="https://remotesite.com/api/$%7Burl%7D%60">https://site.com/api/${url}`</a>);<br>  return result.data as T;<br>}</pre><h3>typeof</h3><p>typeof in classic JavaScript is used to get the name of the type for an object or primitive (ie “object”, “string”, “number” and so forth)</p><pre>const a = { Foo: &quot;Bar&quot; };<br>const b = &quot;Bar&quot;;<br>console.log(typeof a);   // Returns &quot;object&quot;<br>console.log(typeof b);   // Returns &quot;string&quot;</pre><p>It’s not possible to use typeof to get the <em>TypeScript</em> type, because all <em>running </em>code is JavaScript and the type doesn’t exist.</p><pre>type FooType = { Name: string, Age: number };<br>const foo: FooType = { Name: &quot;A&quot;, Age: 1 };<br>console.log(typeof foo);  //&quot;FooType&quot;? No! returns &quot;object&quot;</pre><p>What can typeof in TypeScript be used for then? Well, it can copy existing types of other objects and functions. This is for example valid code:</p><pre>let x: { id: number };</pre><pre>const y: typeof x = { id: 7 };</pre><p>A bigger example could be:</p><pre>const DefaultConfig = {Foo: 1, Bar: 44 };</pre><pre>function LoadFromDisk(): typeof DefaultConfig {</pre><pre>    // Copy the type<br>    let result: typeof DefaultConfig | undefined = undefined;</pre><pre>     result = fs.existsSync(&quot;config.json&quot;)<br>        ? JSON.parse(fs.readFileSync(&quot;config.json&quot;, &quot;utf-8&quot;))<br>        : DefaultConfig;</pre><pre>     return result!;<br>}</pre><h3>ReturnType</h3><p>Consider the following code. The return of DoWork is { a: string, b: string} | undefined and the function must somehow build that result. That might lead to declaring the same object again (see line 3)</p><pre>function DoWork():<strong> { a: string, b: string } | undefined </strong>{</pre><pre>const result: <strong><em>{ a: string, b: string } | undefined</em></strong> = undefined;<br>    /* ... additional code here */<br>    return result;</pre><pre>}</pre><p>There are several ways to resolve this, and the most obvious one is to declare a separate type:</p><pre>type WorkResult = { a: string, b: string };</pre><pre>function DoWork(): WorkResult | undefined {<br>    const result: WorkResult | undefined = undefined;<br>    /* ... additional code here */<br>    return result;<br>}</pre><p>But there are other ways as well.</p><h4>Remote the return value from the function</h4><p>Remove the return information from the function line and allow TypeScript to do its magic. When hovering over DoWork TypeScript knows about the return type. Unfortunately, this decreases readability and, from time to time, TypeScript doesn’t produce a ReturnType that’s sharp enough (or even correct).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*YnpphCfsYfDES2IDtmhfyQ.png" /></figure><h4>Use ReturnType</h4><p>With ReturnType , it’s possible to reference a function and extract the type it’s returning.</p><p><strong>Example 1:</strong></p><pre>function DoWork(): { a: string, b: string} | undefined {</pre><pre>    let result: ReturnType&lt;typeof DoWork&gt; = undefined;</pre><pre>    /* Code that populates the result variable */<br>    result = { a: &quot;a&quot;, b: &quot;b&quot; }</pre><pre>    return result;</pre><pre>}</pre><pre>DoWork();</pre><p><strong>Example 2:</strong></p><p>It might be even more useful if you want to get hold of a type from a module you don’t control. Consider the dependecy of a badly coded database implementation. This way you can guarantee that the type returned will be identical to the type of the referenced module.</p><pre>import { LoadDatabaseEntry } from &#39;./badlycoded&#39;;</pre><pre>function Trimname(): ReturnType&lt;typeof LoadDatabaseEntry&gt; {</pre><pre>    const entry = LoadDatabaseEntry();<br>    entry.Name = entry.Name.trim();<br>    return entry;</pre><pre>}</pre><p>Combing ReturnType with Omit or Pick gives even more control:</p><pre>import { LoadDatabaseEntry } from &#39;./badlycoded&#39;;<br>function Trimname(): <strong>Pick&lt;</strong><em>ReturnType&lt;typeof LoadDatabaseEntry&gt;</em>, <strong>&quot;Name&quot; | &quot;Age&quot;&gt;</strong> {<br>    const entry = LoadDatabaseEntry();<br>    entry.Name = entry.Name.trim();<br>    return entry;<br>}</pre><pre>Trimname()  // Contains only &quot;Name&quot; and &quot;Age&quot;</pre><h3>Multiple returntypes (Union)</h3><p>It’s possible to return for example an object with relevant data (on success) or an error object (with relevant error data) as follows:</p><pre>function LoadData(): <strong>{ Name: string, Age: number }</strong> | {<strong> Error: string }</strong> {<br>     // Simulate a call that succeeds 90% of the time<br>     if (Math.random() &gt; 0.1)<br>         return { Name: &quot;John&quot;, Age: 27 };</pre><pre>      return { Error: &quot;Could not load data.&quot; };</pre><pre>}</pre><h4>Returning different data on success and fail — in more detail:</h4><p>This feature is both good and bad. It will improve on code readability, and it will (at the same time), decrease it. Keep on reading. :)</p><p>Consider this. On Success: true , the relevant data is returned. On Success: false , no data is returned:</p><pre>function LoadData() {</pre><pre>      // Simulate a call that succeeds 90% of the time<br>      if (Math.random() &gt; 0.1)<br>        return { <strong>Success: true,</strong> Name: &quot;John&quot;, Age: 27 };</pre><pre>      return { <strong>Success: false </strong>};<br>}</pre><p>Hovering the function, it reveals that TypeScript has built the correct return type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*et--ZDSgFbHgnearNcswaw.png" /></figure><p>Now, let’s change to this:</p><pre>function LoadData() : { <strong>Success: true</strong>, Name: string, Age: number} | { <strong>Success: false</strong>} {<br>...<br>}</pre><p>TypeScript has been instructed to be aware there’s a <em>difference </em>in the returned data (depending on the result of Success ). Hovering now reveals:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*P9TqfT7xU0JOWz27Vs1Z6w.png" /></figure><p>With IntelliSense; since I’ve checked the data.Success to be true, then I have access to Age and Name values (and <strong><em>only </em></strong>then).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*SjCNZSaCCqt4IjHCRGfOJg.gif" /></figure><p>What’s bad with this approach then? Well, it’s just that. In the below example there’s no check that Success is true, and since TypeScript cannot <em>perfectly </em>decide what to display, the Name and Age values are hidden. This hides away important information for the developer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*94f2EcaoHwBwz2KYYTdjiQ.png" /></figure><h3>Returning multiple values</h3><p>This is not a TypeScript thing, but it’s good to be aware of.</p><pre>function MultipleReturns1() {<br>    return { Foo: &quot;Yes&quot;, Bar: &quot;No&quot; };<br>}</pre><pre>const { Foo, Bar } = MultipleReturns1(); // Destructuring<br>console.log(`Foo=${Foo}, Bar=${Bar}`);   // Prints &quot;Foo=Yes, Bar=No&quot;</pre><p>and with arrays:</p><pre>function MultipleReturns2() {<br>    return [&quot;Yes&quot;, &quot;No&quot;];<br>}</pre><pre>const [a, b] = MultipleReturns2();<br>console.log(`${a} ${b}`);              // Prints &quot;Yes No&quot;</pre><h3>Intersections / “merge” types</h3><p>It’s possible to “merge” two types into a new one. In TypeScript this is described as “Extending a type via intersections”.</p><pre>type User = { Name: string, Age: number }</pre><pre>function LoadData(): <strong>User &amp; { IsNewUser: boolean }</strong> {</pre><pre>   const n = Math.random() &gt; 0.2;<br>   return { Name: &quot;John&quot;, Age: 27, IsNewUser: n};</pre><pre>}</pre><pre>const data = LoadData();<br>console.log(data.IsNewUser);   // OK!</pre><h3>Generics &lt;T&gt;</h3><p>Generics is identified by the type parameter and it’s often identified with the single letter T as in function LoadData<strong><em>&lt;T&gt;</em></strong>() { ... }.</p><p>The easiest way to explain it is: Rather than the function deciding on the type to be returned (ie, “If you call this function it will function return a User-object”), the <em>caller</em> decides on the object to be returned. Basically, the type is a parameter to the function.</p><p>When it comes to functions written for loading data from disk, database, or remote (http://…), then generics is most likely something to consider.</p><p><strong>Example:</strong></p><pre>type User = { Name: string, Age: number }</pre><pre>async function LoadData<strong>&lt;T&gt;</strong>(url: string): Promise&lt;T&gt; {<br>    const result = await axios.get(`<a href="https://remotesite.com/api/$%7Burl%7D%60">https://site.com/api/${url}`</a>);<br>    return result.data as T;<br>}</pre><pre>async function Main() {</pre><pre>   const u1 = await LoadData(&quot;users&quot;);          // u1 is unknown :(<br>   const u2 = await LoadData&lt;User[]&gt;(&quot;users&quot;);  // u2 is User[]</pre><pre>}</pre><p>Depending on function, the Type parameter can be omitted:</p><pre>function Reverse&lt;T&gt;(data: T[]): T[] {<br>    // For the sake of demo only<br>    return data.reverse();<br>}</pre><pre>const sourceData = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;];<br>console.log(Reverse(sourceData));   // Output = [ &#39;C&#39;, &#39;B&#39;, &#39;A&#39; ]</pre><h3>enums</h3><p>Enums in its most basic form is declared as the following:</p><pre>enum FileAccess {<br>    Read,    // Will become the number 0<br>    Write    // Will become the number 1<br>}</pre><pre>const p: FileAccess = FileAccess.Read;</pre><p>Enums that will be stored in a database or similar need to be permanently fixed for the lifetime of the application.</p><pre>// Declare the enum<br>enum eFileAccess {<br>    Read = &quot;ACCESS_READ&quot;,<br>    Write = &quot;ACCESS_WRITE&quot;<br>}</pre><pre>// Use it<br>const p: eFileAccess = eFileAccess.Read;</pre><pre>if (p === eFileAccess.Read)<br>    console.log(&quot;Read access graned&quot;);</pre><pre>console.log(p);  // Returns &quot;ACCESS_READ&quot;</pre><pre>// Convert from string to enum<br>const f = &lt;eFileAccess&gt;&quot;ACCESS_WRITE&quot;;<br>if (f === eFileAccess.Write)<br>    console.log(&quot;Write access granted&quot;);</pre><h4>Bitwise enum / Flags (from c#)</h4><p>Flags aren’t really supported, but can easily be fixed with some bitwise operations.</p><pre>enum eFileAccess {<br>    Read = 1 &lt;&lt; 0,            // 0001 = 1<br>    Write = 1 &lt;&lt; 1,           // 0010 = 2<br>    ReadWrite = Read | Write  // 0011 = 3<br>}</pre><pre>const p: eFileAccess = eFileAccess.ReadWrite;</pre><pre>if (p &amp; eFileAccess.Write) // Bitwise and<br>    console.log(&quot;Write access graned&quot;);</pre><h3>Go Readonly!</h3><p>There are several ways do to this.</p><p><strong>Method 1: </strong>Define a type where readonly is used:</p><pre>type Position = {<br>    readonly x: number;<br>    readonly y: number;<br>}</pre><pre>const a: Position = { x: 1, y: 5 };<br>a.x = 10;   // Error</pre><p><strong>Method 2: </strong>Turn an existing type into readonly.</p><pre>type Position = {<br>    x: number;<br>    y: number;<br>}</pre><pre>function GetPosition(): Readonly&lt;Position&gt; {  // Returns readonly</pre><pre>const result: Position = { x: 0, y: 0 };<br>    result.x = 10;  // Writable<br>    result.y = 20;<br>    return result;</pre><pre>}</pre><pre>let a = GetPosition();<br>a.x = 10;  // Error</pre><h3>Index Signature / the “good” any / KeyValuePair</h3><p>any should most likely be avoided, but sometimes there’s the need for storing data in “key” and “value” pairs. The Index signatures allows for that.</p><pre>const kv: { <strong>[key: string]: string | number</strong> } = {};<br>kv.Name = &quot;Sarah&quot;;<br>kv.Age = 47;</pre><pre>console.log(JSON.stringify(kv)); // {&quot;Name&quot;:&quot;Sarah&quot;,&quot;Age&quot;:47}</pre><p>Looping an index signature with type safety is as easy as:</p><pre>for (const [key, value] of Object.entries(kv))<br>    console.log(`key=${key}, value=${value}`);</pre><p>Finally, if the index signature should be read-only, do the following:</p><pre>type rokv = { <strong>readonly </strong>[x: string]: number; }</pre><pre>const foo: rokv = { &quot;Hour&quot;: 3, &quot;Minute&quot;: 29 };</pre><pre>console.log(foo.Hour);   // Returns 999</pre><pre>foo.Minute = 12;         // Not allowed, is read only</pre><p>And of course, it’s very possible to have objects as values with IntelliSense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*g2R0Epcc2PGYCEpEmBmn8Q.png" /></figure><h3>Interfaces? Or Types?</h3><p>They are almost identical, both in terms of how they’re used and how they’re written. It’s such a personal preference, with few exceptions. With some spaces to align them they compare as:</p><pre>interface Person   { Name: string, Age: number }<br>     type Person = { Name: string, Age: number }</pre><p>Extending both types is possible, but the syntax differs. Read more at <a href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces">https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces</a></p><p>A significant difference is that Interfaces with the same name are <em>merged</em>! This is especially important when there’s a need for modifying already existing interfaces (keep on see “Modifying the global namespace” below).</p><pre>interface Person { Name: string }<br>interface Person { Age: number }<br>const newUser: Person = { Name: &quot;Linda&quot;, Age: 80 };   // OK!</pre><h3>Modifying the global namespace (global.name)</h3><p>On occasion, there’s this need for having a global variable available across your entire Node.js project. It might be a constant, a function, or a logger.</p><p>Globals is defined in <strong>.d.ts</strong> files, as this one declarations.d.ts. Place it under “src”.</p><p><strong>Important! </strong>Set the environment variable TS_NODE_FILES to the word “true”. This will enable the include/ exlude config settings in tsconfig.json</p><pre>declare global {<br>   namespace NodeJS {<br>    interface Global {<br>       LicenseKey: string<br>    }<br>  }<br>}</pre><pre>export { };  // Don&#39;t forget this </pre><p>:!: Got “ES2015 module syntax is preferred over custom TypeScript modules and namespaces”? Do not use .ts naming, use .d.ts .</p><p>To access the global variable, function or object, you just need to:</p><pre>function Main() {<br>   global.LicenseKey = &quot;ABC123&quot;;<br>}</pre><p>It’s possible to declare the variable on the very root. An example would be to have a logger object globally, which is accessible without including it in every file. For this scenario there are a couple of things to consider:</p><p><strong>declarations.d.ts:</strong></p><pre>type Logger = {<br>    debug: (p: string) =&gt; void<br>}</pre><pre>declare global {</pre><pre>    // eslint-disable-next-line no-var<br>    declare var logger: Logger;<br>}</pre><pre>export { };</pre><p>The biggest challenge with global objects such as this logger is that it requires super early initialization. Make an index.ts which initializes needed global variables, and <em>only that</em>. This file in turn includes a <em>single</em> file, like main.ts , where the rest of init runs. Done right, the index.tswill be able to run its code <em>before </em>including the main.ts file.</p><pre># Init my (fake) global logger (note: without global-prefix)<br>logger.debug = (iData: string) =&gt; { console.log(iData); };</pre><pre># Use it<br>logger.debug(&quot;Logger initialized, booting system.&quot;);</pre><h3>Environment variables and the global namespace</h3><p>Finally, let’s investigate how to modify the global namespace to get type check on environment variables. The process.env.VARIABLENAME can be configured as:</p><pre>declare global {<br>    namespace NodeJS {<br>        interface ProcessEnv {<br>            NODE_ENV: &quot;production&quot; | &quot;development&quot;,<br>            VARIABLENAME: string | undefined,<br>        }<br>    }<br>}<br>export { };</pre><p>Usage:</p><pre>if (process.env.NODE_ENV === &quot;development&quot;)<br>   console.log(`VARIABLENAME=${process.env.VARIABLENAME}`);</pre><h3>Modifying the Express namespace</h3><h3>More info on using global variables</h3><p>I’ve written an additional article on the matter, read it <a href="https://medium.com/typescript-and-global-variables-in-node-js-59c4bf40cb31">here</a>.</p><h3>Modifying the Express namespace</h3><pre>import &quot;express&quot;; // Modifies global namespace, so include it!</pre><pre>declare global {</pre><pre>namespace Express {<br>        interface Request {<br>            token: string,<br>            userId: string<br>        }<br>    }<br>}</pre><pre>export { };</pre><p>Add middleware to decode our user (from bearer, cookie or similar) and store the verified user in the req object. It’s possible to store just the ID of the user, or an actual object with more data.</p><pre>import * as Express from &quot;express&quot;;</pre><pre>app.use((req: Express.Request, res: Express.Response, next: Express.NextFunction) =&gt; {</pre><pre>    // Do work to decode req.headers.authorization here<br>    req.token = &quot;thetoken&quot;;<br>    req.userId = &quot;usr00001&quot;;</pre><pre>    next();</pre><pre>});</pre><p>In your routes, it’s as easy as:</p><pre>app.get(`/test`, async function (req: Express.Request, res: Express.Response) {</pre><pre>   if (!req.userId)<br>    // ... Not authenticated<br>    res.status(401).json({ Success: false });<br>   else<br>    // ...All ok<br>    res.json({ Success: true });<br>  });</pre><h3>Promise vs async</h3><p>Let’s begin with establishing that for most use cases they can be considered to be identical. Below are two functions, one returns a new Promise and the other uses async (with type safety). These two functions are called in four different ways.</p><pre>// Two different implementations doing the same thing</pre><pre>async function DoSomething(): Promise&lt;number&gt; {<br>  return Math.random();<br>}</pre><pre>function DoSomething2() {<br> return <strong>new Promise&lt;number&gt;</strong>((<em>resolve: (result: number) =&gt; void</em>) =&gt; {<br>    resolve(Math.random());<br> });</pre><pre>}</pre><pre>// Test function</pre><pre>async function TestThemAll() {</pre><pre>// Test both using &quot;.then&quot; syntax</pre><pre>DoSomething().then(result =&gt; {<br>        console.log(`DoSomething returned: ${result}`);<br>    });</pre><pre>DoSomething2().then(result =&gt; {<br>        console.log(`DoSomething2 returned: ${result}`);<br>    });</pre><pre>// Test them both using &quot;await&quot; syntax</pre><pre>console.log(`DoSomething returned: ${await DoSomething()}`);<br>    console.log(`DoSomething2 returned: ${await DoSomething2()}`);</pre><pre>}</pre><pre>TestThemAll();</pre><p>… but what about callbacks? … please. No.</p><h3>Starting a TypeScript project as-is</h3><p>There is no need to transpile to out and run the code from there, it can be done on the fly (even with breakpoints and stepping in VSCode).</p><p>Start a TypeScript project from the command line:</p><pre>set TS_NODE_FILES=true &amp; node -r ts-node/register src/index.ts</pre><p>In VSCode, there needs to be a .vscode\launch.json file. Add add the following and press F5 to run.</p><pre>{<br> &quot;version&quot;: &quot;0.2.0&quot;,<br> &quot;configurations&quot;: [<br>  {<br>   &quot;name&quot;: &quot;Debug typescript&quot;,<br>   &quot;type&quot;: &quot;node&quot;,<br>   &quot;request&quot;: &quot;launch&quot;,<br>   &quot;smartStep&quot;: false,<br>   &quot;sourceMaps&quot;: true,<br>   &quot;args&quot;: [&quot;${workspaceRoot}/<strong>src/index.ts</strong>&quot;],<br>   &quot;runtimeArgs&quot;: [<br>            &quot;-r&quot;,<br>            &quot;ts-node/register/transpile-only&quot;<br>   ],<br>   &quot;cwd&quot;: &quot;${workspaceRoot}&quot;,<br>   &quot;protocol&quot;: &quot;inspector&quot;,<br>   &quot;internalConsoleOptions&quot;: &quot;openOnSessionStart&quot;,<br>   &quot;env&quot;: {<br>    &quot;TS_NODE_IGNORE&quot;: &quot;false&quot;,<br>   <strong> &quot;TS_NODE_FILES&quot;: &quot;true&quot;, // Respect include/exclude in tsconfig.json =&gt; will read declaration files</strong><br>    &quot;NODE_ENV&quot;: &quot;development&quot;<br>   },<br>   &quot;skipFiles&quot;: [<br>    &quot;&lt;node_internals&gt;/*&quot;,<br>    &quot;&lt;node_internals&gt;/**&quot;,<br>    &quot;&lt;node_internals&gt;/**/*&quot;,<br>    &quot;${workspaceRoot}/node_modules/**&quot;,<br>    &quot;${workspaceRoot}/node_modules/**/*&quot;<br>   ],<br>   &quot;stopOnEntry&quot;: false,<br>   &quot;outputCapture&quot;: &quot;std&quot;,<br>  },<br> ]<br>}</pre><p>If you want to change what to run when pressing F5, open the vscode command palette (ctrl-shift-p) and search for Debug: Select and start debugging .</p><h3>Some tool tips!</h3><p>Finally getting to the end. Lets wrap up with some misc tool tips.</p><h4>tsc</h4><p>Running tsc while developing will help to track errors on the project level. VSCode in combination of eslint and the <a href="https://marketplace.visualstudio.com/items?itemName=usernamehw.errorlens">Error Lens</a> plugin will show local errors.</p><p><strong>Building once</strong></p><p>Open a terminal and type tsc -b -v to build the project a single time (with verbose on). The current working directory should be the same folder as tsconfig.json.</p><p><strong>Building continuously (watch &amp; incremental)</strong></p><p>Much better is to turn on watch for file changes -w and, to that, use incremental -i for faster transpiling. All in all use:</p><pre>tsc -b -v -i -w</pre><h4>typesync</h4><p>Not all modules found on npmjs.com has types built-in. <a href="https://www.npmjs.com/package/typesync">typesync </a>scans the project and tries to find needed types:</p><pre>📦 project1 — package.json (1 new typings added, 0 unused typings removed)<br>└─ + <a href="http://twitter.com/types/express">@types/express</a></pre><p>In the cases where no types exist in the module itself or there are no separate ones, then you are on your own. Either write the definitions manually or use declare module to set the module as any. For doing the latter, create a definition.d.ts with the following contents:</p><pre>declare module &#39;&lt;module name here&gt;&#39;;</pre><pre>// Example:<br>declare module &#39;rfc822-validate&#39;;</pre><h4>npm-check</h4><p>Use <a href="https://www.npmjs.com/package/npm-check">npm-check</a> tool to upgrade your dependencies. Run it with npm-check -d or npm-check -d -g</p><h4>deadfile</h4><p>Finding unused files is somewhat tricky, because there are so many ways to use files. <a href="https://www.npmjs.com/package/deadfile">deadfile </a>does a decent job.</p><pre>deadfile .\\src\\index.ts --exclude out --exclude log</pre><h3>Enjoy :)</h3><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2656c2f5d17" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-guide-to-kickstarting-backend-typescript-development-e2656c2f5d17">The Guide to Kickstarting Backend TypeScript Development</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>