<?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 Sean Maxwell on Medium]]></title>
        <description><![CDATA[Stories by Sean Maxwell on Medium]]></description>
        <link>https://medium.com/@seanpmaxwell1?source=rss-2b1b1f90d011------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*C2LAaJyzVolgKEYIAuV_KQ.png</url>
            <title>Stories by Sean Maxwell on Medium</title>
            <link>https://medium.com/@seanpmaxwell1?source=rss-2b1b1f90d011------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 01:09:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@seanpmaxwell1/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[Setup Express with TypeScript in 3 Easy Steps]]></title>
            <link>https://levelup.gitconnected.com/setup-express-with-typescript-in-3-easy-steps-484772062e01?source=rss-2b1b1f90d011------2</link>
            <guid isPermaLink="false">https://medium.com/p/484772062e01</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Sean Maxwell]]></dc:creator>
            <pubDate>Tue, 16 Apr 2019 01:48:29 GMT</pubDate>
            <atom:updated>2019-07-05T15:46:55.099Z</atom:updated>
            <content:encoded><![CDATA[<h4>Create an Express server in a classic object-oriented style</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knOS0UnwOWHGvgtDXOppeg.png" /><figcaption>Express on steroids</figcaption></figure><p>Are you attracted to the ease-of-use and rapid-development of NodeJS with the Express web-server, but worried about the scalability and type-safety needed for large applications? Not to fear, TypeScript has got you covered. It still provides the advantages of a scripting language with the robustness of a static language like C# or Java. Learning TypeScript is trivial if you already know JavaScript, configuring it just requires a little extra setup.</p><blockquote>Just to point out, I know there are some articles on Medium which show you how to use Express with TypeScript, but they either spend a lot of time talking about why you should use TypeScript and/or they don’t emphasize setting up Express in an object-oriented fashion. The point of this article is to show you the best and easiest configuration for TypeScript while developing for NodeJS/Express.</blockquote><h4>Edit Jun 2019</h4><p>If you’re starting a project from scratch there is a npm library which can do all of this for us now named <em>express-generator-typescript</em>.</p><p><a href="https://www.npmjs.com/package/express-generator-typescript">express-generator-typescript</a></p><p>All the source code for this tutorial is available on GitHub here. You should observe the corresponding files/folders while you read the tutorial.</p><p><a href="https://github.com/seanpmaxwell/ExpressTypeScript">seanpmaxwell/ExpressTypeScript</a></p><h3>Setup TypeScript</h3><p>During development, we can run our TypeScript code directly from the .ts files that we create. For production though, we should transpile them to JavaScript so our server can be run directly from NodeJS. To configure how our TypeScript is transpiled and to set rules for the styling our code, we need to create the tsconfig.json<em> </em>and a tslint.json files respectively. Using tslint is not required but is extremely handy for enforcing coding standards and will lead to much cleaner code in the long run.</p><p>Create a new folder for your project and at the root add tsconfig.json with the following content:</p><blockquote>Notice the exclude option on line 23 which shows /src/public/. We’re not going to cover the front-end for this tutorial, but once you do get around to adding some front-end content, it should go there.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78d9f33eb62f5f6032908334d4e5543f/href">https://medium.com/media/78d9f33eb62f5f6032908334d4e5543f/href</a></iframe><p>Now add the following code for the tslint.json file. I tend to use the recommended settings with a few tweaks. Feel free to play around with these settings if you want.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e0aee874fe9a11297699d3707240878/href">https://medium.com/media/5e0aee874fe9a11297699d3707240878/href</a></iframe><p>To allow us to execute some code, let’s create a start script which will boot up our server. Since we don’t have a server yet, just have it print out &quot;hello world&quot; for now. Create the folder and file src/start.ts and add the following 2 lines:</p><blockquote>tslint is disabled because it pushes us not to use console.log() and it’s not good to leave it in production code.</blockquote><pre>// tslint:disable-next-line<br>console.log(&#39;hello world&#39;);</pre><p>We don’t want to have to restart everything manually when we make a code change, so let’s use nodemon to watch for changes in our files and re-execute our start script.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2a2f6abc4f9833dab27c667d690ce63/href">https://medium.com/media/b2a2f6abc4f9833dab27c667d690ce63/href</a></iframe><p>Great! We got everything we need to start developing in TypeScript, we just need to install dependencies. Run npm init if you haven’t done so yet to your project in an npm package, then install the following npm libraries:</p><pre>npm i -D ts-node nodemon typescript tslint</pre><p>So we can start things with ease without having to enter a bunch of long commands in the console each time we want to start developing, let’s add a script to package.json to run the start script through nodemon with ts-node.</p><p>See line 8 below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ac048895a20317f12a0344aaeec597c/href">https://medium.com/media/1ac048895a20317f12a0344aaeec597c/href</a></iframe><p>Run npm run start-dev and you should see hello world output to the console.</p><h3>Setup Express</h3><p>Now that TypeScript is all setup and running well, let’s create a simple ExpressJS webserver and few routes. We could use ExpressJS directly but then we wouldn’t take advantage of TypeScript. It would be nice to create classes with methods instead of having to type let router = express.Router(), router.get/put/post, app.use(router) and all that over and over again.</p><p>To stay closer to the MVC pattern and utilize OO style programming, I recommend OvernightJS to add controllers and route decorators to Express. Yeah I know what you’re going to say, <em>“Aren’t there frameworks out there like NestJS and ts-express-decorators which can decorate Express routes?</em>” Yes, that’s true, but these are all massive frameworks with entire websites dedicated to their documentation. Overnight is just a simple, small collection of libraries for adding decorators to Express and a couple other things. It’s not an abstraction layer on top of Express, and you can learn it in about 10 minutes if you’re already familiar with Express.</p><p><a href="https://github.com/seanpmaxwell/overnight">seanpmaxwell/overnight</a></p><p>Let’s install Express and Overnight and spin-up a web-server:</p><blockquote>The <em>body-parser </em>package is so we can send our data as JSON.</blockquote><ul><li>npm i -s express body-parser @overnightjs/core @overnightjs/logger</li><li>npm i -D <a href="http://twitter.com/types/node">@types/node</a> @types/express</li></ul><p>Under src/, create a file for the server (mine is ExampleServer.ts) and create a class of the same name. Then add another folder/file controllers/ExampleController.ts. We’ll implement the controller first then import it into our server file.</p><p>Add the following content to the controller file:</p><blockquote>Notice we created a method for every route just to see each one in action. The <em>Logger</em> class is handy because it can be configured to print to a file, the console, turned-off completely, or something custom depending on your server environment.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7cfd3a7562a00c6278ae7200b0cc87c/href">https://medium.com/media/b7cfd3a7562a00c6278ae7200b0cc87c/href</a></iframe><p>When you’re done with the controller, make sure to add an index.ts file to controllers/<em>,</em> with the line export * from ‘./ExampleController’; so that any new controller files created in the future can be easily added with just an extra line of code.</p><p>In the server, import the controllers and the extend the class with Overnight’s Server export. By extending Server, you will have access to the Express instance with this.app, which you can interact with just like any normal Express instance made with require(‘express’)().</p><p>Controllers must be instantiated and added as an array to super.addControllers(…) to activate your routes. Make sure to add your controllers after setting the middleware but before starting the server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf4055111a9f25f926075e9acc6fd671/href">https://medium.com/media/cf4055111a9f25f926075e9acc6fd671/href</a></iframe><p>Now that we have our server and controllers, we just need to boot everything from the start script. Import the server, instantiate it, and call start(portNumber).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/858ae84f2a182825b86b8f87b7da5137/href">https://medium.com/media/858ae84f2a182825b86b8f87b7da5137/href</a></iframe><p>Once you see &quot;[someTimestamp]: Example server started on port: 3000&quot; print out to the console, you can open up an API calling tool of your choice (i.e. Postman) and fire of requests to the server. If you followed my examples to the letter, you should see the :msg part of your routes print out to the console.</p><h3>Build your code</h3><p>Now that we have a fully functional development server up and running, all we need to is build it for production. In case you delete .ts files as you develop, you should remove the build/ folder every time you transpile or you’ll end up with junk .js files .</p><p>To start the production code, we need to run build/start.js instead of src/start.ts. Let’s add two more scripts to package.json to build and run the code for production.</p><blockquote>The tsc command tranpsiles our code. See line 9 below:</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dd7ec408794df023de5ebcf918e14e5/href">https://medium.com/media/5dd7ec408794df023de5ebcf918e14e5/href</a></iframe><p>Once your server is started, all your routes should work just the same as they did before.</p><p>Please star the tutorial’s repo and the OvernightJS repo on GitHub if you found this article helpful. Happy web-deving :)</p><p><a href="https://gitconnected.com/learn/typescript">Learn TypeScript - Best TypeScript Tutorials (2020) | gitconnected</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=484772062e01" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/setup-express-with-typescript-in-3-easy-steps-484772062e01">Setup Express with TypeScript in 3 Easy Steps</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trool: a spreadsheet rule engine for NodeJS/TypeScript]]></title>
            <link>https://levelup.gitconnected.com/trool-a-spreadsheet-rule-engine-for-nodejs-typescript-edcb05fca231?source=rss-2b1b1f90d011------2</link>
            <guid isPermaLink="false">https://medium.com/p/edcb05fca231</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rule-engine]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[spreadsheets]]></category>
            <dc:creator><![CDATA[Sean Maxwell]]></dc:creator>
            <pubDate>Mon, 01 Apr 2019 15:10:59 GMT</pubDate>
            <atom:updated>2019-04-03T03:04:28.423Z</atom:updated>
            <content:encoded><![CDATA[<p>Get the rules out of your code so non-engineers can make updates overtime</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*L_5Oh0QLfMxn1p3JFYcPaw.png" /><figcaption>Trool makes it easy to update your program overtime!</figcaption></figure><h3>Trool Introduction</h3><p>Trool is a simple npm library for NodeJS which allows you to create rules for your program in a spreadsheet-style format. Engineering time for businesses can be expensive: you want to keep that to a minimum. The problem is your program may need lots of small updates over time depending on business needs. It’s a waste of money to call on programmers every time a small change needs to be made. Instead of hard-coding these small changes in your code, why not move them to a spreadsheet, so you or non-engineers on your team can quickly make the changes.</p><blockquote>While Trool can be used directly with JavaScript (ES5 or ES6) in NodeJS, all the documentation is in TypeScript and you are encouraged to use that.</blockquote><h3>Links</h3><ul><li><a href="https://www.npmjs.com/package/trool">trool</a></li><li><a href="https://github.com/seanpmaxwell/trool">seanpmaxwell/Trool</a></li></ul><h3>How it works</h3><p>To use Trool, you just need to create the classes to be updated and the spreadsheet, pass them all to a single Trool method, and you’ll receive back all of the same objects but with updates made according to your rules. The spreadsheet works by checking attributes on the provided objects and calling methods on each depending on how conditions are met. If you want to reuse values in multiple places throughout the spreadsheet, you can create <strong><em>Imports </em></strong>which are simple key/value pair lists. Imports can be hard-coded in the spreadsheet or passed through NodeJS code. Here’s a sample of what a spreadsheet might look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0oyWLdXoH2P2ry3ihgCt_g.png" /><figcaption>Trool spreadsheet for setting ticket prices based on visitor age and party size</figcaption></figure><h3>Installation</h3><pre>$ npm install --save trool</pre><pre>// the library includes the typings files so you don&#39;t need to install @types/trool</pre><h3>Tutorial</h3><h4>Setup Trool</h4><p>After you’ve installed Trool, import and instantiate it in your program. You can pass a boolean to the constructor depending on whether or not you want Trool to show any logging data while it runs. You should turn this on during development and leave it off for production.</p><pre>import Trool from &#39;trool&#39;;<br><br>class PriceCalculator {<br><br>    private trool: Trool;<br><br>    constructor() {<br>        this.trool = new Trool(true);<br>    }<br>}</pre><h4>Fact</h4><p>To use Trool, you must first understand the concept of a <strong>Fact</strong>. A fact is an instance-object or array of instance-objects that need to be updated. To create a fact, implement a TypeScript class and make sure that every attribute has getters and setters. If you look at cell 2A in the screenshot above, you can see that the content of the cell is <strong>Table</strong>: Visitors. Visitors is a fact made using an array of Visitor instance-objects.</p><p>After you’ve created your TypeScript classes, the facts must be passed to Trool in a fact-holder object. The fact-holder object is a JSON object with the key being the name of the fact to be accessed in the spreadsheet and the value being the array of instance-objects. So with <strong>Table</strong>: Visitors, we need to setup a fact-holder object with Visitors as the key and a single visitor or array of visitors as the value.</p><pre>public calculate() {</pre><pre>    const factsHolder = {<br>        Visitors: [new Visitor(), new Visitor()]<br>    }<br>}</pre><h4>Decision-Table</h4><p>After setting up your facts, open up Excel, LibreOffice Calc, or some other spreadsheet tool of your choice. To update facts we need to setup a <strong>decision-table</strong>. A decision-table is a group of operations (columns) and rules (rows). If a rule passes, operations will be called to update the fact. If a fact is an array, the decision-table will loop through each instance-object and apply its logic to each value.</p><p>The first cell of the table specifies the fact and it must follow the exact format <strong>Table</strong>: &quot;Name of the fact&quot; or an error will be thrown. Next create at least one <strong>Condition</strong> column and one <strong>Action</strong> column. If all the conditions pass, the action will be executed. There’s no limit to the number of conditions and actions you implement, but you must specify one of each and all conditions must come before all actions.</p><p>In the second row of the decision-table, create the operations for the conditions and actions. A condition must be a boolean operation and in the format factAttribute operator $param. In other words, $param must be on the right-side of the operation. The attribute on the left side of the operation could be a regular method or a getter, but is has to be one of them and exist on the instance-object. If it does not, Trool will throw an error.</p><p>An action is the operation to be fired when all conditions evaluate to true. This operation can be a setter or a regular method on the fact. If using a regular method, multiple $param can be specified.</p><p>A <strong>Rule</strong> is a list of values to be passed to the condition and action operations. The first cell of the rule must specify a rule-name which can be any value but cannot be blank. On a decision-table, Trool will loop through the cells in each rule then move on to the next rule. The value in the cell will replace the $param value in the operation and the operation will execute. If a cell is blank for a condition, it will automatically evaluate to true. If all conditions are true for a rule, the actions which have values for that rule will execute. If a cell is blank though, that action-operation will not execute. A cell value must be something that can be evaluated with a comparison operator and it’s highly recommended that you stick with primitives and not use objects as values.</p><p>Let’s look at a simple decision-table with 1 condition, 1 action, and 2 rules (<em>“Set Price — Regular”</em> and <em>“Set Price — Season”</em>). Trool will iterate through the Tickets array, and first look at the getter for option and compare it to the cell values for each rule. In the first rule (<em>Set Price — Regular</em>), the table will see if each Ticket’s option attribute is set to <em>“Regular”</em>. If it is, the setter for price will be called and set the value 70. After <em>“Set Price — Regular” </em>finishes, the table will go on to <em>“Set Price — Season”</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*iLB9US-jNmnw1RYlPy_6Iw.png" /><figcaption>Decision-Table for setting default ticket prices</figcaption></figure><p>Thanks to Trool, if your ticket prices change periodically or you want to add new ticket options in the future, you don’t have to waste valuable engineering time!</p><h4>Imports</h4><p>Suppose for a moment there’s a specific value that needs to be used in multiple tables and you need let’s say, and string value to always be spelled a certain way. For the ticket option <em>“Season”</em>, you may always want to make sure it’s spelled <em>Season</em> and not <em>Seasonal</em> or something. This is where imports come in handy. It’s generally a good idea to use string values through imports and not directly to prevent spelling errors. Imports can be implemented in the spreadsheet or passed through code. For larger applications, you may have imports created dynamically and need to pass them through the code. For simple apps, it’s recommended you keep your imports in the spreadsheet.</p><p>To create an import in the spreadsheet, start with the cell <strong>Import:</strong> “Import Name”. The next rows will be added as key/value pairs to the import until it reaches an empty line, table, or new import. You should keep your imports and decision-tables separated by blank lines for readability purposes.</p><p>Here’s an example of an import with 2 key/value pairs. With this import, instead of doing “Season” for the rule <em>“Set Price — Season”</em>, you could say TicketTypes.SEASON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*wz9ljFTGK7g1IeKJbqP2BA.png" /><figcaption>The TicketTypes Import</figcaption></figure><p>If you want to pass imports through your code, just like the facts, they must be passed via a holder object. The key must be the name of the import and the value the import itself. For the import<em> </em>TicketTypes that we just did in the spreadsheet, here is the equivalent doing the same thing in code:</p><pre>public calculate(): void {</pre><pre>    const factsHolder = {<br>        Visitors: [new Visitor(), new Visitor()]<br>    }</pre><pre>    const importsHolder = {<br>        TicketTypes: {<br>            REGULAR: &#39;Regular&#39;,<br>            SEASON: &#39;Season&#39;<br>        }<br>    }<br>}</pre><h4>Using Trool</h4><p>Once you’re done setting up the spreadsheet, make sure to export it as a <em>.csv </em>file. On the Trool instance, call the method applyRules(…), passing in the path to the csv file, the facts object, and optionally, any imports you decided to create in code and not in the spreadsheet. This method is asynchronous and returns a Promise containing an identical facts-holder object but with all the facts updated according to action-operations that have been called. Now your NodeJS program can proceed with all the updated values it needs.</p><pre>public <strong>async</strong> calculate(): Promise&lt;void&gt; {</pre><pre>    const factsHolder = {<br>        Visitors: [new Visitor(), new Visitor()]<br>    }</pre><pre>    const importsHolder = {<br>        TicketTypes: {<br>            REGULAR: &#39;Regular&#39;,<br>            SEASON: &#39;Season&#39;<br>        }<br>    }</pre><pre>    try {<br>        const csvFilePath = path.join(__dirname,&#39;filename.csv&#39;);</pre><pre>        const <strong>updatedFacts</strong> = <strong>await</strong> this.trool.applyRules( csvFilePath, factsHolder, importsHolder);<br><br>    } catch (err) {<br>        console.log(err.message);<br>    }<br>}</pre><h3>Conclusion</h3><p>Hopefully Trool become of great use to you and drastically cuts down on your engineering time. There are some more rules for using Trool than what could be specified in one article. I highly encourage you to read the README via the GitHub link posted above to avoid errors when implementing your decision-tables.</p><p>Please star the GitHub repo if you found this article/library helpful :)</p><p><a href="https://gitconnected.com/learn/node-js">Learn Node.js - Best Node.js Tutorials (2019) | gitconnected</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edcb05fca231" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/trool-a-spreadsheet-rule-engine-for-nodejs-typescript-edcb05fca231">Trool: a spreadsheet rule engine for NodeJS/TypeScript</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up a Full-Stack TypeScript Application: featuring Express and React]]></title>
            <link>https://levelup.gitconnected.com/setting-up-a-full-stack-typescript-application-featuring-express-and-react-ccfe07f2ea47?source=rss-2b1b1f90d011------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccfe07f2ea47</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Sean Maxwell]]></dc:creator>
            <pubDate>Tue, 29 Jan 2019 16:36:26 GMT</pubDate>
            <atom:updated>2019-07-06T18:43:36.109Z</atom:updated>
            <content:encoded><![CDATA[<h4>Great for projects of any size… startups and enterprises!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Jzkk7h4cxLf_yBXVF54NQ.png" /><figcaption>The TypeScript world is limitless</figcaption></figure><p>Many will tell you that NodeJS is better suited for small projects and that static, compiled languages like Java/C# are better for large enterprise applications. This is where TypeScript comes in handy; it gives you the rapid development of a scripting language combined with the type safety of a static language. If you already know JavaScript, the learning curve for TypeScript is extremely small. TypeScript just requires a little extra setup at the beginning because it’s well… a superset and not technically a language.</p><blockquote>Just to point it out, I’m sure there are tutorials all over the web showing you how to setup TypeScript for React or NodeJS. But the ones I’ve run into have been pretty piecemeal and I’ve never really read one that was comprehensive enough. The point of this article is to show you how to setup TypeScript for both front and back-end development, and also debug, unit-test, and then build everything together for production.</blockquote><h3>Edit June 2019</h3><p>There is now an npm application which can handle most of the back-end portion of this tutorial for us. It’s called <em>express-generator-typescript</em>.</p><p><a href="https://www.npmjs.com/package/express-generator-typescript">express-generator-typescript</a></p><p>All the source code is available at the following repository. You should observe the corresponding files/folders in the repo while reading this article.</p><p><a href="https://github.com/seanpmaxwell/TypeScriptFullStackShell">seanpmaxwell/TypeScriptFullStackShell</a></p><h3>Folder Hierarchy</h3><p>To keep things organized we’re going to put all the configuration and dependencies for our back-end at the root of our directory. We’ll generate everything needed for the front-end using the <em>create-react-app</em> npm module and nest it in the <strong>src/public/react/</strong> folder. The reason for putting our React app here and not in its own separate folder at the root is that as your web-application grows, you might end up serving some pages that are not part of the main React app or you could even end up serving multiple react apps.</p><p>To give an example, you might end up having all the front-end content accessible by regular users served at one Express route contained within a single React app. At the same time, content used by your site Administrators could be served at a different Express route in another React app. For this tutorial though, we’re only going to setup one React project.</p><p>Create a folder to serve as the root and give it the name of whatever your app is going to be. I’m just going to call mine root. Run npm init inside of it to turn it into an npm package and generate a <strong>package.json</strong> file. Create a another a file named <strong>src/</strong> to hold our front-end and back-end code and another named <strong>util/</strong> which will hold our files for production building.</p><pre>root/<br>  src/<br>    public/<br>      react/<br>        demo-react/<br>  util/<br>  package.json</pre><h3>TypeScript for the Back-End</h3><h4>Setup ts-node</h4><p>To start coding in TypeScript, we need to install the dependencies that will transpile our code and then create configuration files (although they are not strictly required) that set rules for how they are transpiled. At the root of your app install <em>ts-node and nodemon</em>, which runs our .ts files directly during development and can also restart our server when changes are detected, and <em>typescript</em>, to turn our <em>.ts</em> files in <em>.js</em> files. These modules are for development so make sure to use the -D option.</p><ul><li>npm i -D ts-node nodemon typescript tslint</li></ul><p>To specify rules for transpilation, create a file named <strong>tsconfig.json </strong>at <strong>root/ </strong>and paste in the following contents. If you plan on debugging with an IDE like Webstorm or VsCode, we need to generate <strong>.js.map</strong> files which is what “sourcemap” on line 8 is for.</p><p>The unit-test test files we’ll eventually create will end with .test.ts and aren’t needed for production so make sure to exclude those in addition to any front-end folders, which will have their own build scripts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bedada2d82df9254d1df6a4ed30a2043/href">https://medium.com/media/bedada2d82df9254d1df6a4ed30a2043/href</a></iframe><p>To enforce a set of coding standards for your TypeScript, create another file named <strong>tslint.json</strong>. I tend to set mine pretty strict cause I like to follow convention, but feel free to play around with these settings if you want.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66c5df2d6c756968fcf7b0d01b067604/href">https://medium.com/media/66c5df2d6c756968fcf7b0d01b067604/href</a></iframe><h4>Create a Server</h4><p>Now we can finally start writing some TypeScript. Under <strong>src/</strong> create a server file which will configure and run Express. We could use the plain <em>express</em> module by itself but I think we should take advantage of the fact that we’re using TypeScript. OvernightJS is a simple library to wrap decorators around Express Router objects so you don’t have to instantiate one for every API that you create. It’s not an abstraction on top of Express nor is it meant to change the way you interact with it. That’s why I like it more than some of these large frameworks like <em>NestJS</em> or <em>typescript-express-decorators</em>.</p><p><a href="https://www.npmjs.com/package/@overnightjs/core">@overnightjs/core</a></p><p>Install @overnightjs/core, create a server file, and extend the Server class from whatever you name your server class.</p><ul><li>npm i -s overnightjs/core</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a86ad610a93d2885abe10dccd797d835/href">https://medium.com/media/a86ad610a93d2885abe10dccd797d835/href</a></iframe><h4>Create a start.ts file</h4><p>I’m sure you’re ready to see your code in action… but first!! To make running/building our application a little faster let’s create a <strong>start.ts </strong>file which can kick everything off. Notice the “scripts” key in our <strong>package.json</strong> file. Each property within “scripts” is like a mini-bash script that we can run with npm run “whatever the key is”. This along with the <strong>start.ts</strong> file will enable us to run/test/build our code with just a small set of npm run … commands.</p><p>Add another file to <strong>root/</strong> named <strong>start.ts</strong> and give it some if-else statements to check whether we’re running for development/production or testing. For the moment, let’s just start the server. We’ll complete this file as we go through different sections.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dafb6871ad70df74c7bee66bcdfbef1b/href">https://medium.com/media/dafb6871ad70df74c7bee66bcdfbef1b/href</a></iframe><p>To avoid having to start and stop Express every time the code changes, let’s use <em>nodemon</em> to restart ts-node whenever there’s a change in a source file. nodemon can import it settings directly from the command-line or from a file: a file is easier so let’s use that. Place the file <strong>nodemon.json</strong> under <strong>util/</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91b7012b405abd60303ec4826f35a1ab/href">https://medium.com/media/91b7012b405abd60303ec4826f35a1ab/href</a></iframe><p>So other developers don’t have to enter a long command each time, let’s add nodemon as a property to <strong>package.json</strong>’s “scripts”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b9875127331a627db5a74de0b3c4420/href">https://medium.com/media/2b9875127331a627db5a74de0b3c4420/href</a></iframe><p>The command on line 7 will start ts-node with the settings from <strong>tsconfig.json</strong> file, and restart the server in development mode every time we run:</p><ul><li>npm run start-dev</li></ul><p>Go ahead and run the command and you should see the SERVER_START_MSG print out to the console. Make a change to the server file (port or start message) and you should the see the Express server restart and the changes immediately.</p><p>Congrats!! You’ve see up a Express/TypeScript development server.</p><h3>Making an API</h3><p>Having an Express server which doesn’t do anything isn’t much fun to play around with, so using OvernightJS let’s make a single, simple API that just prints out some text and sends back a JSON response. Create a folder under <strong>src/</strong> named <strong>controllers/</strong>, add a controller file and name it whatever you want: I named mine <strong>DemoController.ts</strong>. Give it a single API for now (you can add more later) using the OvernightJS’s route decorators, and give the route a try/catch block which handles a response for errors. This will be useful for showing you how to unit-test later on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93be65bf4eae0eecd12070b3a7ed3d2b/href">https://medium.com/media/93be65bf4eae0eecd12070b3a7ed3d2b/href</a></iframe><p>Back in the server file, setup Express to parse JSONs and import/activate the controller we just created. So we don’t trigger an error when visiting <strong>localhost:3001</strong> in the browser, let’s also setup a default response for that too when running the server in development mode.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07aeeec5b08409acd2debd096042a39b/href">https://medium.com/media/07aeeec5b08409acd2debd096042a39b/href</a></iframe><p>Restart nodemon, and fire off a GET request, using an API calling tool of your choice (such as Postman), to <strong>localhost:3001/api/say-hello/:name</strong>. Make sure that that you get a return value and that the Express route fires an error when you pass in makeitfail as the parameter.</p><p>If all is well we can move on to our front-end!</p><h3>Creating a React App</h3><p>This is going to require much less configuration because <em>create-react-app</em> will spin up a shell for our project and import all the necessary dependencies. All we have to do is connect the front to the back so we can develop each one separately while still activating our Express APIs from within React.</p><p>Download the <em>create-react-app</em> globally (or use <em>npx</em>), navigate to <strong>src/public/react/</strong>,<strong> </strong>and create a new TypeScript React project:</p><pre>cd src/public/react/<br>npx create-react-app demo-react --typescript</pre><p>Navigate to <strong>demo-react/</strong>, run npm start, and at <strong>localhost:3000</strong> you should see the React sample page.</p><h4>Linking the Front and Back together during Development</h4><p>Now that we have a front and back-end, we need to setup a proxy so your http request will go to to Express instead of the React development server. To make sure our configuration works, let’s put some code inside React that sends a request to our ‘say-hello’ API. To keep it simple, just add something that gets fired automatically for right now. If you want to display a response in the browser you’ll need to convert the response to a JSON format (see line 12 below). Using <em>fetch</em>, I added a get request in <strong>demo-react/src/App.tsx</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb8c5f778909ee306bcdd9b926d5a038/href">https://medium.com/media/bb8c5f778909ee306bcdd9b926d5a038/href</a></iframe><p>Now to channel our requests to the back-end, add the proxy property to the React app’s <strong>package.json</strong> file and set the value to the url:port that Express is running on. See line 21 below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d949b365a6496c5c15cd0e3db88ce796/href">https://medium.com/media/d949b365a6496c5c15cd0e3db88ce796/href</a></iframe><p>If React’s dev server is currently running, save the file (you should see the browser refresh automatically) and an alert should appear with the API’s response.</p><h3>Unit-Testing the Back-End</h3><p>Congrats, you’ve got a full-stack Express/React app setup for development. The tools you need for testing the front are packaged for you with <em>create-react-app</em>,<em> </em>but since we’ve been doing the back from scratch let’s go over how to start testing for it. There are a number of testing tools you can use but the ones I like the best are <em>Jasmine</em> and <em>Supertest</em>. Jasmine allows you to write business-driven-development test with describe() and it(). Supertest enables us to fire off API calls inside our TypScript code passing along any data we want to and providing a callback for the responses where we make our tests’ assertions.</p><p>Install the two dependencies for testing and their corresponding <em>@types/</em> packages:</p><ul><li>npm i -D jasmine @types/jasmine supertest @types/supertest</li></ul><h4>Test Server</h4><p>Create another file in the <strong>controllers/demo</strong> folder with the same name as your last controller file but appended with <strong>.test.ts</strong>. To make the the API calls, Supertest needs to get an instance of our Express app. We don’t actually want to start our server with this.app.listen though, so instead of using the main <strong>DemoServer.ts</strong> configuration, let’s create a new server file just for testing. All it needs to do is activate one controller and return the Express instance. Oh and one more thing, we’ll still need to pass it whatever middleware we did in our main server file. Place this file in a <strong>controllers/shared/</strong> folder and import the server class at the top of your test file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/784448d31cc7cb3364e572da6d010d55/href">https://medium.com/media/784448d31cc7cb3364e572da6d010d55/href</a></iframe><blockquote>This is another thing that makes OvernightJS so great. It’s trivial to spin up new Express apps for testing purposes.</blockquote><h4>Your first Unit-Test</h4><p>In your test file, configure Supertest in the beforeall() method and setup one unit-test for each controller route. Make sure to add an assertion for every possible pathway the user can trigger in each unit-test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a70118ea5e1dbf97de7a28f63314092/href">https://medium.com/media/9a70118ea5e1dbf97de7a28f63314092/href</a></iframe><h4>Configure Jasmine</h4><p>We could run Jasmine directly from the command line using jasmine, but if we wanted to debug our test files just like any other node script, we would need to run Jasmine from a <strong>.js</strong> file. To do, so let’s add a configuration for Jasmine in <strong>start.ts</strong>.</p><p>Configure Jasmine to load the test files from the <strong>src/</strong> directory (lines 15–22), if we run <strong>start.ts</strong> with the test argument. When writing tests, you might not want to run all at once; you might just want to run a single test file. That’s why we check for a 2nd argument (which will be the path for a test file), and pass it to Jasmine’s execute method if it exists.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f09bbec66c2fe6f033e0fdc60c78c920/href">https://medium.com/media/f09bbec66c2fe6f033e0fdc60c78c920/href</a></iframe><p>Give the following property to <strong>package.json</strong> “scripts” so we can run our unit-tests with npm run test.</p><ul><li>“test”: &quot;ts-node ./src/start.ts test&quot;</li></ul><p>If you want pass in a unit-test, all you need to run is:</p><ul><li>npm test -- &quot;path to the unit-test file&quot; (i.e. controllers/DemoController)</li></ul><h3>Building for Production</h3><p>After you’re done developing and testing your code, you’ll want to build it. ts-node should only be used during development, so we’ll need generate .js files for production.</p><h4>Automate the build process</h4><p>To build both the back-end and the front-end for production, we don’t want to have to manually transpile our TypeScript, build our code, navigate to the front-end directory, build that code, then move the bundled React app to our top level build folder every time we’re ready for production. So let’s create a script that can do all of that for us and then configure that app to be run with a single command.</p><p>Configure this script to transpile our back-end code (skipping the test files), navigate to the React app, build that, give the output folder the same name as the React app’s folder (remember to be keep consistency), then move that to where the back-end code was built to. The source maps are only needed for development, so use the sourceMap false option on line 9 below so we don’t generate a bunch of <strong>.js.map</strong> files.I develop in Linux, so I use Bash; however, if you’re on Windows, you’ll have to look up the equivalent Batch or PowerShell commands.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7556a321e62d5305d29df157dd892dd9/href">https://medium.com/media/7556a321e62d5305d29df157dd892dd9/href</a></iframe><h4>Modify the server file to serve the front-end for production</h4><p>In development mode, Express just sends a single line to the browser which tells us which port Express is running on. But in production, Express needs to serve React from the same port that it’s running on. Since our entire front-end right now is contained in a single React app, we can point our static and views directory both there.</p><p>Add another method to the server file and append the if statement in the constructor which sets the <strong>views/</strong> and <strong>static/</strong> directories for Express when in production mode.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a487a0dcf15b06df4d2ecc02c81a1780/href">https://medium.com/media/a487a0dcf15b06df4d2ecc02c81a1780/href</a></iframe><p>To activate our build script and make it easy to start our entire app in production mode, let’s modify the <strong>package.json</strong> files one last time to run our build script and start the code for production by running the built start script with the environment set to production.</p><p>Notice lines 7 and 10 in the snippet below. We can build for production with npm run build and start in production mode with npm start.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/454c61653bb042096573d960154a3cca/href">https://medium.com/media/454c61653bb042096573d960154a3cca/href</a></iframe><p>Now when you start the Express server in production mode and navigate to the same route you started it under in the browser, you should see the React app displayed.</p><h3>Please star the repo and the OvernightJS repo on GitHub if you found this article helpful. Happy web-deving :)</h3><figure><a href="https://levelup.gitconnected.com/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6CoI_MRyZ1JInNPsBSHtA.png" /></a></figure><ul><li><a href="https://gitconnected.com/learn/typescript">Learn TypeScript - Best TypeScript Tutorials (2020) | gitconnected</a></li><li><a href="https://gitconnected.com/learn/react">Learn React - Best React Tutorials (2019) | gitconnected</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccfe07f2ea47" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/setting-up-a-full-stack-typescript-application-featuring-express-and-react-ccfe07f2ea47">Setting up a Full-Stack TypeScript Application: featuring Express and React</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Object-Oriented Concepts in a Nutshell]]></title>
            <link>https://levelup.gitconnected.com/typescript-object-oriented-concepts-in-a-nutshell-cb2fdeeffe6e?source=rss-2b1b1f90d011------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb2fdeeffe6e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Sean Maxwell]]></dc:creator>
            <pubDate>Mon, 17 Dec 2018 15:45:55 GMT</pubDate>
            <atom:updated>2018-12-20T19:33:33.062Z</atom:updated>
            <content:encoded><![CDATA[<h4>All the major aspects of TypeScript objects in one place so you don’t have to google around for them</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gk2K5x3uZkR_mN5p9S37Xw.png" /><figcaption>(TypeScript === JavaScript with Superpowers) =&gt; true</figcaption></figure><p>If you come from a traditional object-oriented (OO) background like me and are daunted by the quirks of JavaScript — not to fear — because TypeScript has got you covered. This tutorial is going to skim through all the major points of TypeScript objects while giving examples along way and showing you when they come in handy. The features of TypeScript objects overlap heavily with traditional OO languages like Java and C#, so some of these you may already be familiar with these points if you’re a seasoned programmer. If not, this will be a great overview of OO style programming.</p><h3>TypeScript Objects vs JavaScript Objects</h3><p>TypeScript objects are just syntax-sugar for JavaScript function-objects. There’s a lot of repetitive code when it comes to using function-objects as classes in JavaScript, that’s why class was implemented for ES6. TypeScript takes ES6 classes to a higher plane of reality by adding — not only types — but also object features such as public, private, abstract, etc. If you’re interested in learning more about quirks of JavaScript function-objects (which I highly recommend doing) please checkout my Medium article <a href="https://levelup.gitconnected.com/the-javascript-object-paradigm-and-prototypes-explained-simply-e9cb9eaa49aa">here</a>.</p><h3>Object Overview</h3><p>Objects in TypeScript (like in all of OO programming) are useful because they let us model our program off of real world scenarios. Objects are instances (a particular variable with that object as its value type) of classes. Think of classes as just a group methods and variables. Let’s say we wanted to have a program called <em>PetStore</em> that only sells cats and dogs. A dog could have attributes like age and breed but also methods like getRelativeAge, if we want the age in dog years. If we’re talking about a particular dog object such as Spot or Bingo, who have values set for their attributes, then those objects are instances of the Dog class.</p><p>Classes are implemented using the class keyword, just like in ES6. To create an object we call the class with the new keyword, which triggers the constructor and returns an <em>instance-object</em> just like in regular JavaScript. Since objects in JavaScript are technically just a set of key/value pairs, I like to use the term instance-object to refer to objects returned with the new keyword.</p><p>Spot is an instance-object of Dog.</p><pre>class Dog<br>{<br>    age: number<br>    breed: string</pre><pre>    constructor(age: number, breed: string)<br>    {<br>        this.age = age<br>        this.breed = string<br>    }</pre><pre>    getRelativeAge(): number<br>    {<br>        return this.age * 7<br>    }<br>}</pre><pre>let Spot = new Dog(2, &#39;Labrador&#39;)</pre><p>Equivalent using function-objects in ES5.</p><pre>function Dog(age, breed)<br>{<br>    this.age = age<br>    this.breed = breed<br>}</pre><pre>Dog.prototype.getRelativeAge = function() {<br>    return this.age * 7<br>}</pre><pre>var Spot = new Dog(2, &#39;Labrador&#39;)</pre><h3>Inheritance</h3><p>Now that you know how to make objects and can see how they work under the hood in JavaScript, let’s start learning about TypeScript inheritance. In our PetStore program, we’re selling dogs and cats but there could be different breeds of dogs and cats right? Also dogs and cats might share some of the same attributes like age and weight. Super classes, (aka parent classes) allow for related objects to be grouped together so that they can inherit similar attributes. To inherit from a parent classes we use the extends keyword. When you extend a class, all attributes and methods with be passed down. Instead of creating age and weight each time we add a new animal to our pet store, we can now just expand upon a parent Animal class. Multi-level inheritance is also possible by extending child classes.</p><p>The super keyword serves two roles in inheritance. First it acts as a function and is used in the parent class’s constructor. It has to be called before this in the child object constructor. The other is that it allows us to access methods (but NOT attributes) of the parent object.</p><p>Animal is the parent class of Dog:</p><pre>class Animal<br>{<br>    age: number<br>    breed: string</pre><pre>    constructor(age: number, breed: string)<br>    { <br>        this.age = age<br>        this.breed = breed<br>    }</pre><pre>    makeSound_(sound: string): void<br>    {<br>        console.log(sound)<br>        console.log(sound)<br>        console.log(sound)<br>    }<br>}</pre><p>Basic inheritance using super:</p><pre>class Dog extends Animal<br>{<br>    playsFetch: boolean</pre><pre>    constructor(age: number, breed: string, playsFetch: boolean)<br>    {<br>         <strong>super</strong>(age, breed) // call parent constructor<br>         this.playsFetch = playsFetch<br>    }</pre><pre>    makeSound(): void<br>    {<br>        <strong>super</strong>.makeSound_(&#39;woof woof&#39;)<br>    }</pre><pre>    getAgeInHumanYears(): number<br>    {<br>        return this.age * 7    // super.age will throw error<br>    }<br>}<br></pre><pre>class Cat extends Animal<br>{<br>    constructor(age: number, breed: string)<br>    {<br>        <strong>super</strong>(age, breed)<br>    }</pre><pre>    makeSound(): void<br>    {<br>        <strong>super</strong>.makeSound_(&#39;meow meow&#39;)<br>    }<br>}</pre><blockquote>JavaScript ES6 inheritance works the same way, but in TypeScript there is an additional access-control feature when working with parent classes. ES6 also does not allow for class level variables to be defined outside of methods.</blockquote><h3>Access-Control</h3><p>Access-control refers to where we can use a class’s attributes and methods. If you’ve ever skimmed through an OO language’s code, you might have noticed keywords like public, private, and protected. Let’s go over what each one of these is for and why they are useful.</p><p>Suppose our PetStore program has a class named PetStore. If this class wants to call methods on our Dog objects, then those methods will need to be marked public. When a method or variable is public that means it can be accessed by another part our program. When we don’t have any modifier on a variable or method, it’s the same as marking it public.</p><pre>class Dog<br>{<br>    <strong>public</strong> name: string // leaving out <strong>&#39;public&#39;</strong> would work too<br>}</pre><pre>class PetStore<br>{<br>    dogs: Array&lt;Dog&gt;</pre><pre>    printAllDogNames(): void<br>    {<br>        this.dogs.forEach(dog =&gt; {<br>            console.log(dog.name)<br>        })<br>    }<br>}</pre><p>Allowing other coders to directly access attributes of objects generally is not a good idea though. It’s better to use <em>getters</em> and <em>setters </em>to access/modify class properties so we can pass some logic when setting a value and prevent errors. For example, a dog’s name shouldn’t be falsey and it should be under a certain length. A realistic dog name would never be more than 10–20 characters. To make an class variable/method only accessible within that class we should mark it private. TypeScript classes have built in get and set modifiers which will trigger our getters and setters whenever a property is trying to be accessed.</p><pre>class Dog<br>{<br>    <strong>private</strong> _name: string // beginning underscore is convention</pre><pre>    <strong>get</strong> name(): string<br>    {<br>       return this._name<br>    }</pre><pre>    <strong>set</strong> name(name: string): void<br>    {<br>        if(!name || name.length &gt; 20) {<br>            throw new Error(&#39;Name invalid&#39;)<br>        }<br>        else {<br>            this._name = name<br>        }<br>    }<br>}</pre><pre>class PetStore<br>{<br>    <strong>private</strong> _dogs: Array&lt;Dog&gt; // we changed this to private too</pre><pre>    constructor()<br>    {<br>        this._dogs = [new Dog()]<br>        this._dogs[0].name = &#39;Fido&#39; // will call <strong>&#39;set&#39;<br>    }</strong></pre><pre>    printAllDogNames(): void<br>    {<br>        this._dogs.forEach(dog =&gt; {<br>            console.log(dog.name) // will call <strong>&#39;get&#39;</strong><br>        })<br>    }<br>}</pre><p>Lastly, let’s look at the protected keyword. Protected means that a variable/method can only be accessed in child classes of the parent. Remember the makeSound method of the Animal parent class? We shouldn’t be able to access that method externally on any class that inherits from animal or animal itself because not animals make sounds. I like to post-pend protected attributes with an ending underscore, although it’s not convention.</p><pre>class Animal<br>{<br>    <strong>protected</strong> makeSound_(sound: string): void<br>    {<br>        console.log(sound)<br>        console.log(sound)<br>        console.log(sound)<br>    }<br>}</pre><pre>class Dog extends Animal<br>{<br>    makeSound(): void<br>    {<br>        super.makeSound_(&#39;woof woof&#39;)<br>    }<br>}</pre><pre>class PetStore<br>{</pre><pre>    makeSomeSounds(): void<br>    {<br>        let dog = new Dog()<br>        dog.makeSound() // =&gt; <strong>&#39;woof woof&#39; &#39;woof woof&#39; &#39;woof woof&#39;</strong></pre><pre>        let animal = new Animal()<br>        animal.makeSound_() // =&gt; <strong>NOT ALLOWED</strong><br>    }<br>}</pre><h3>Other Modifiers</h3><p>There are 2 other modifiers that important to mention when talking about TypeScript classes: static and readonly. If we want to access a property on a class without having to go through the trouble of returning an instance-object (calling the object with new), then we can mark it as static and it will be set on the class (function-object) itself. This is useful for methods and class variables which are not dependent on any dynamic property. For example, a dog will always be the same species.</p><pre>class Dog<br>{<br>    <strong>static</strong> species = &#39;Canis Familaris&#39;<br>    age = 10<br>}</pre><pre>class PetStore<br>{<br>    printSpecies(): void<br>    {<br>        console.log(Dog.species) // =&gt; <strong>&#39;Canis Familaris&#39;</strong><br>        console.log(Dog.age) // =&gt; <strong>undefined</strong><br>    }<br>}</pre><p>The readonly keyword is pretty self-explanatory. It’s used for class level variables and means that the value cannot be reassigned. Values that are initialized when the class is created and you know are never going to change should be readonly. Our Dog class’s species property is a good example. No matter what attributes we assign to dog it will always be the same species.</p><pre>class Dog<br>{<br>    static<strong> readonly</strong> species = &#39;Canis Familaris&#39;<br>}</pre><pre>class PetStore<br>{<br>    printSpecies(): void<br>    {<br>        console.log(Dog.species) // =&gt; <strong>&#39;Canis Familaris&#39;</strong><br>        Dog.species = &#39;Terdus Maximus&#39; // =&gt; <strong>NOT ALLOWED</strong><br>    }<br>}</pre><h3>Interfaces</h3><p>Whenever we want to say that an object being passed has a specific set of attributes, we can use an interface. Interfaces are nifty little tools that can be used for several situations.</p><p>The most immediate thing that comes to mind is testing. Suppose we have a method in our Dog class that does an I/O call, and we wanted to unit test a method in our PetStore class which called that method. We don’t want to fire an I/O call every time a unit-test is run but we still need an object which evaluates as the Dog type. Let’s create an iDog interface which specifies a method for both the regular and mock class that we create for our unit-test.</p><pre>interface iDog<br>{<br>    getPedigree: Function<br>}</pre><pre>class Dog implements iDog<br>{<br>    getPedigree(): Promise&lt;Pedigree&gt;<br>    {<br>        return someThirdPartyIoCall(&#39;...&#39;)<br>    }<br>}</pre><pre>class MockDog implements iDog<br>{<br>    getPedigree(): Promise&lt;Pedigree&gt;<br>    {<br>        return new DummyPedigreeObject()<br>    }<br>}</pre><pre>async function methodToBeTested(dog: iDog): Promise&lt;void&gt;<br>{<br>    try {<br>        let pedigree = await dog.getPedigree()<br>        // do assertions here<br>    }<br>    catch(err) {<br>        console.log(err)<br>    }<br>}</pre><pre><br>// Real World<br>methodToBeTested(new Dog())</pre><pre><br>// During Testing<br>methodToBeTested(new MockDog()) </pre><p>This is only one small example of using interfaces and there are plenty of more uses. I recommend checking the TypeScript Docs <a href="https://www.typescriptlang.org/docs/handbook/interfaces.html">here</a> for more information.</p><h3>Abstract Classes and Methods</h3><p>Think of abstract classes as kind of a cross between regular parent classes and interfaces. Abstract classes define attributes for other classes like interfaces do, but some of their methods may contain implementation unlike interfaces. A method without implementation must be marked abstract, and so must its containing object. Abstract classes may not be instantiated (can’t use new) and useful for when you know you’ll never need the parent class directly.</p><p>For both cats and dogs we have the age property and want to know each one’s age in human years. The method for defining this though will be different depending on the animal. Let’s use an abstract class.</p><pre><strong>abstract</strong> class Animal<br>{<br>    protected age_: number</pre><pre>    <strong>abstract</strong> getRelativeAge(): number;<br>}</pre><pre>class Dog extends Animal<br>{<br>    getRelativeAge(): number<br>    {<br>        return this.age_ * 7<br>    }<br>}</pre><pre>class Cat extends Animal<br>{<br>    getRelativeAge(): number<br>    {<br>        return this.age_ * 6<br>    }<br>}</pre><blockquote><strong>Note</strong>: This is not meant to be an accurate representation of how to properly calculate a cat’s and a dog’s age.</blockquote><h3>Conclusion</h3><p>There is way more to TypeScript classes than what was covered in this tutorial, but hopefully this quick easy rundown helped put things into perspective a little better. Whether or not you or others intend to use TypeScript extensively, the object-oriented concepts covered here overlap so much with other OO languages it’s still a very useful read. Typescript is also nice for learning OO because such a less formal language than Java, C#, or C++.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb2fdeeffe6e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/typescript-object-oriented-concepts-in-a-nutshell-cb2fdeeffe6e">TypeScript Object-Oriented Concepts in a Nutshell</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The JavaScript Object Paradigm and Prototypes Explained Simply]]></title>
            <link>https://levelup.gitconnected.com/the-javascript-object-paradigm-and-prototypes-explained-simply-e9cb9eaa49aa?source=rss-2b1b1f90d011------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9cb9eaa49aa</guid>
            <category><![CDATA[prototype-chain]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[prototype]]></category>
            <dc:creator><![CDATA[Sean Maxwell]]></dc:creator>
            <pubDate>Tue, 27 Nov 2018 16:05:40 GMT</pubDate>
            <atom:updated>2019-08-11T18:01:08.560Z</atom:updated>
            <content:encoded><![CDATA[<h4>All the confusing points about JavaScript objects revealed so you can stop hating them as much</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*bF20HEclFo2afymdAsgQdg.png" /><figcaption>Ughhh, why does JavaScript have to be like this?</figcaption></figure><p>To many new developers the JavaScript world may seem pretty irksome, especially to those from a traditional object-oriented background. Just googling around for some JavaScript code and explanations might reveal pretty messy code and confusing terminology. To make things easier, this article is going to give you an overview of simple, prototype-based inheritance, so you can have a good foundation for programming with JavaScript.</p><blockquote>Just to point out, I know articles trying to explain JavaScript objects have been done to death, but I felt like I’ve never really read one that explained them thoroughly or clearly. They often focus on inheritance exclusively while leaving out other important points or don’t give enough examples. The purpose here is to give you a brief overview of JavaScript objects and prototype-inheritance in the simplest way possible.</blockquote><h4>What are objects?</h4><p>Objects at the most basic level can be thought of a list of key/value pairs with the key always being a string and the value being… well anything else. It’s similar to what you might call a <em>“map”</em> in other languages. Everything that you type in JavaScript that is not a primitive (see the last section for more info about primitives) is an object. Objects make it easy to package and move data around and creating new ones is more trivial than in other object-oriented languages like Java/C#.</p><p>When talking about objects you’ll often hear the term<em> “property”</em> used. This refers to a specific key/value pair on an object. To give you an idea of what objects look like, we’ll start off with a simple example of an object with two properties: age and weight.</p><pre>var Dog = {<br>    age: 8,<br>    weight: 65<br>}</pre><blockquote><strong>Note</strong>: Our code-snippet just now was an example of using an object-literal. An object-literal strictly refers to the code within and including the curly-braces. An object-literal is not a variable or a return value.</blockquote><h4>Functions are Objects</h4><p>As mentioned, everything that is not a primitive is an object, that includes functions too… I know weird right? Kinda hard to think of functions as a group of key/value pairs. Since functions are objects they are often referred to as <em>function-objects</em>. A function-object is a special group of key/value pairs with specific properties for executing code and passing down values. We’ll go over what these properties are in the next section. First let’s talk about why functions are important.</p><p>You could say that function-objects have two primary purposes. If we want to create a chuck of logic that executes, we can use a function-object: just like <em>“methods”</em> in any other programming language. The next purpose is where JavaScript gets kinda funky. If we want to create objects with both values and methods, and perhaps some logic to set those values, we would also use function-objects. This is where you could think of function-objects as behaving like <em>“classes”</em> in object-oriented languages (i.e. Java/C#).</p><blockquote><strong>Note</strong>: You will hear the term “<em>method”</em> sometimes used in JavaScript. In JavaScript a method refers to a function-object which exists as a property of a containing object.</blockquote><p>In the standard case, functions in JavaScript look like functions in any other language; they execute a chunk logic to perform a specific task. In the following snippet, bark is function-object executing code.</p><pre>function bark() {<br>    console.log(&#39;woof woof&#39;)<br>}</pre><pre>bark() =&gt; &#39;woof woof&#39;</pre><p>If we wanted to package a small group of data, like our 2 properties in the Dog object from before, then a simple key/value pair list works just fine. What if we want to create multiple Dog objects though? Maybe some values need to be static and others dynamic. This is where function-objects come in handy. When we call a function with new, an object (aka <em>instance-object</em>) is returned with properties set from the this keyword inside the function.</p><pre>function Dog(age, weight) {<br>    this.species = &#39;Canis Familiaris&#39;<br>    this.age = age<br>    this.weight = weight<br>    this.bark = bark &lt;-- bark() from prev snippet<br>}</pre><pre>// Spot and Bingo are <strong>&#39;instance-objects&#39;</strong> of Dog<br>var Spot = <strong>new</strong> Dog(8, 65)<br>var Bingo = <strong>new</strong> Dog(10, 70)</pre><pre>Spot.species =&gt; &#39;Canis Familiaris&#39;</pre><pre>// bark is a <strong>&#39;method&#39;</strong> of Dog<br>Bingo.bark() =&gt; &#39;woof woof&#39;</pre><h4>Objects vs Prototypes</h4><p>Now that you have a decent understanding of objects and more importantly function-objects, let’s talk about prototypes. You’ve often heard that JavaScript is a prototype-based language. So does that mean that objects and prototypes are the same thing? Well not exactly. <em>Prototypes are a special type of object and exist as a property on function-objects.</em> When we try to access a key on a function-object, JavaScript will look at its prototype property to see if it’s there. If not it will go up the <strong>prototype-chain</strong> to try to find it. To understand the prototype-chain, we need to learn about functions and inheritance.</p><h4>Functions and Inheritance</h4><p>Whenever an instance-object is returned from a function call using new, it is given a property with the key __proto__. The value of this property is the prototype property of the function that created it.</p><pre>Bingo.__proto__ === Dog.prototype<br>Spot.__proto__ === Dog.prototype</pre><p>If we try to access a property on an instance-object and it’s not there, JavaScript will first go to __proto__ and see if it’s on the parent function’s prototype. To see this in action, let’s set a property on the prototype key for our Dog object and when we call Spot[&#39;whatever the key name is&#39;] or Bingo[&#39;whatever the key name is&#39;] we’ll get that same value. This will work even after both dog instance-objects have been created.</p><pre>Dog.prototype.bark = function() {<br>    console.log(&#39;woof woof&#39;)<br>}</pre><pre>Spot.bark() // =&gt; &#39;woof woof&#39;<br>Bingo.bark() // =&gt; &#39;woof woof&#39;</pre><p>Setting methods this way (in contrast to using this inside of functions) is especially useful because the method implementation will only occur once instead of every time new is called. This will save memory and increase performance.</p><h4>Let’s dig a little deeper into inheritance now!</h4><p>At the heart of all JavaScript inheritance is the Object keyword, which is a function-object. All instance-objects inherit from it. When we create an object-literal, JavaScript under the hood is actually calling new Object(). The new object’s __proto__ will point to Object’s prototype. So all objects made from object-literals are actually instance-objects of Object. This provides us with a lot of useful methods like hasOwnProperty, which can tell us if a property exists on an object. If we try to access a property directly on a function-object, JavaScript will look at prototype first and then move up the chain using __proto__ on the prototype.</p><p>Let’s look at a couple of examples of JavaScript moving up the prototype-chain to access hasOwnProperty on some objects.</p><p>Object-literal:</p><pre>var insect = {legs: 6}</pre><pre>// insect.__proto__ === Object.prototype<br>// insect.hasOwnProperty === Object.prototype.hasOwnProperty</pre><pre>insect.hasOwnProperty(&#39;legs&#39;) // =&gt; true</pre><p>Instance-Object:</p><pre>var Bingo = new Dog()</pre><pre>// Bingo.__proto__ === Dog.prototype<br>// Dog.prototype.__proto__ === Object.prototype</pre><pre>Bingo.hasOwnProperty(&#39;weight&#39;) // =&gt; true</pre><p>Directly on Function-object:</p><pre>function Foo() {<br>    this.something = &#39;blah&#39;<br>}</pre><pre>// Foo.prototype.__proto__ === Object.prototype</pre><pre>Foo.hasOwnProperty(&#39;name&#39;) // =&gt; true<br>Foo.hasOwnProperty(&#39;something&#39;) // =&gt; false, set on instance-object not on the function</pre><h4>What about the __proto__ of Function-Objects?</h4><p>As explained, __proto__ helps link objects to the prototypes they inherit from. What about calling __proto__ directly on function-objects though? JavaScript actually has a built-in function-object called Function. Every function’s __proto__ property points to Function.prototype, which is a function but does not have the prototype property and returns undefined. Function.prototype defines the default behavior that all functions inherit from. Like all prototype properties of function-objects, it still has__proto__ which points to Object.prototype.</p><pre>Dog.__proto__ === Function.prototype       <br>Object.__proto__ === Function.prototype    <br>Function.__proto__ === Function.prototype  </pre><pre>Function.prototype.__proto__ === Object.prototype</pre><h4>Whew that was a lot…</h4><p>All that was a bit confusing right? Maybe this pic can help make things a little simpler. Notice Object.prototype is where everything originates from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*KNCFqc7YytARCUXJGgYn1Q.png" /><figcaption>The Prototype-Chain</figcaption></figure><h4>Multi-Level Inheritance</h4><p>When we say inheritance we typically think of instance-objects returned from functions. With prototype you can also do multiple levels of inheritance and have function-objects inherit from other function-objects. All you have to do is set the child function-object’s prototype to another instance of the parent function-object’s prototype. Then all properties of the parent will be copied. If the parent function receives arguments, such as age and weight in Dog, use .call to set the this property for the child-object.</p><p>Labrador inherits from Dog:</p><pre>function Labrador(furColor, age, weight) {<br>    this.furColor = furColor<br>    this.breed = &#39;labrador&#39;<br>    Dog.call(this, age, weight)<br>}</pre><pre>Labrador.prototype = Object.create(Dog.prototype)</pre><pre>var Fido = new Labrador(&#39;white&#39;, 4, 41)<br>Fido.bark()</pre><h4>Classes</h4><p>Classes in JavaScript, which were created for ES6, are just syntax sugar on top of function-objects. Instead of having to type prototype over-and-over again to define methods on functions, with the class keyword we can just define a group of methods inside of a class. With the extends keyword, classes can inherit from other classes without having to do Object.create and Object.call. I like using classes more, but keep in mind not all browsers may support them (ES6). That’s why tools like Babel were created.</p><p>Using function-objects:</p><pre>function Dog(age, weight) {<br>    this.age = age<br>    this.weight = weight<br>}</pre><pre>Dog.prototype.bark = function() {console.log(&#39;woof woof&#39;)}</pre><pre><br>function Labrador(furColor, age, weight) {<br>    this.furColor = furColor<br>    this.breed = &#39;labrador&#39;<br>    Dog.call(this, age, weight)<br>}</pre><pre>Labrador.prototype = Object.create(Dog.prototype)</pre><p>Equivalent using classes:</p><pre>class Dog {<br>    constructor(age, weight) {<br>        this.age = age<br>        this.weight = weight<br>    }</pre><pre>    bark() {<br>        console.log(&#39;woof woof&#39;)<br>    }<br>}</pre><pre>class Labrador extends Dog {<br>    constructor(furColor, age, weight) {<br>        super(age, weight)<br>        this.furColor = furColor<br>        this.breed = &#39;labrador&#39;<br>    }<br>}</pre><h4>Objects vs Primitives</h4><p>JavaScript code in essence boils down to two basic types: primitives and objects. There are 5 primitives in JavaScript: boolean, number, string, null, and undefined. Primitives are just simple values with no properties on them. 3 of the primitives: boolean, number, and string all have object counterparts which JavaScript will coerce during certain operations. For example, &quot;some string&quot;.length will call new String() under-the-hood and wrap the instance-object returned around the string primitive so the length property can be accessed. As mentioned, all instance-objects inherit from Object. So with a string you can still use methods like hasOwnProperty.</p><pre>// String.prototype.__proto__ === Object.prototype</pre><pre>String.hasOwnProperty(&#39;length&#39;)  // =&gt; true</pre><h3>Conclusion</h3><p>Yeah yeah I know that was a headache; it seemed like and endless barrage of prototype this and __proto__ that. Personally, I think inheritance in JavaScript is way more convoluted than it needs to be that’s why I use TypeScript. If you’re working your way towards becoming a solid front-end developer though, it’s helpful to know and makes you appreciate why super-sets of JavaScript exist.</p><p>Please hit the clap button if you found this article helpful. Happy web-deving!</p><figure><a href="https://levelup.gitconnected.com/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9uYu-fFL3hIQLGVu0o-EQ.png" /></a></figure><p><a href="https://gitconnected.com/learn/javascript">Learn JavaScript - Best JavaScript Tutorials (2019) | gitconnected</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9cb9eaa49aa" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-javascript-object-paradigm-and-prototypes-explained-simply-e9cb9eaa49aa">The JavaScript Object Paradigm and Prototypes Explained Simply</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 things to learn for becoming a solid full-stack JavaScript developer]]></title>
            <link>https://levelup.gitconnected.com/10-things-to-learn-for-becoming-a-solid-full-stack-javascript-developer-8b76467711ac?source=rss-2b1b1f90d011------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b76467711ac</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[full-stack]]></category>
            <dc:creator><![CDATA[Sean Maxwell]]></dc:creator>
            <pubDate>Mon, 19 Nov 2018 16:02:33 GMT</pubDate>
            <atom:updated>2019-07-12T20:06:00.129Z</atom:updated>
            <content:encoded><![CDATA[<h4>…and some tips for getting started</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*YfEOtukQSNXUOBcgZjuKLg.png" /><figcaption>The JavaScript world is endless</figcaption></figure><p>In the world of programming, finding beauty in simplicity means we want to reuse the same tool/language wherever possible and avoid as much boiler plate code as we can. If you’re a web developer, you’re probably aware of the fact that JavaScript can be used as both a front and a back-end language. Maybe you’re already considering full-stack JavaScript or actively using it. Regardless of where you are, here’s a list of 10 things you should learn if you want to be a full-stack JavaScript developer.</p><p>Quick Note: being a full-stack developer means being able to write server code (back-end) running on the OS which grabs data from the database and displays it to the user in the web browser (front-end).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1/0*mjk8bMXgg_xTLp06.gif" /></figure><h4>1. Have a fundamental understanding of JavaScript</h4><p>Of course you can’t do full-stack JavaScript development (or full-stack any web development for that matter), without learning JavaScript itself. You don’t need to be a grand-master to get started, but should should have a basic understanding of the paradigm and control flow. Contrary to what some may say, JavaScript is not a hard language. It’s got its fair share of quirks and gotchas, but once you get used to these, it’s a really fun language to work with. A lot of the example code you run into out there might be sloppy, but when used right, JavaScript can actually be written pretty eloquently.</p><p>The fact that it’s a both a dynamic and a prototype based language might feel a bit irksome to those from a traditional object-oriented background, but here’s a quick tip to get started I wish I knew early on. JavaScript basically boils down to 2 types: objects and primitives. The 5 primitives are boolean, number, string, null, and undefined; everything else is an object. Functions, classes in ES6, and arrays are all objects under the hood. Objects at the most basic level can be thought as a set of key/value pairs with the key always being a string and the value being… well whatever you want: a primitive, another object, a function, array etc. Feel free to check out this <a href="https://levelup.gitconnected.com/the-javascript-object-paradigm-and-prototypes-explained-simply-e9cb9eaa49aa">article</a> if you want to learn more about JavaScript objects.</p><p>Probably the next most important aspect of JavaScript is its heavy emphasis on asynchronous programming. This allows the main thread of your program’s execution to continue while waiting for some other method to finish. The two main ways this is done is through callbacks and promises. This medium article <a href="https://medium.com/@siddharthac6/javascript-execution-of-synchronous-and-asynchronous-codes-40f3a199e687">here</a> is a great introduction to asynchronous and synchronous programming and this <a href="https://levelup.gitconnected.com/understand-javascript-promises-by-building-a-promise-from-scratch-84c0fd855720">one</a> provides a good overview of promises.</p><h4>2. Front-End framework</h4><p>Single page applications are the way to go nowadays due to performance advantages. Learning a front-end framework is the most practical way to make one. The three big ones are Angular, React, and Vue, but of course those aren’t your only options. There’s a bit of a feud going on in the JavaScript world as to which one is the best. If you google “Angular vs React”, you’ll see quite a few articles scattered across the internet comparing each one’s advantages and disadvantages. I’m partial to Angular for the reasons mentioned <a href="https://levelup.gitconnected.com/deciding-between-angular-and-react-for-hobbyist-web-developers-9247def281fb">here</a>. I will concede though that there are some situations where React or Vue might be a better fit. I’d recommend reading a number of these articles and getting a high level understanding of the differences, then choosing the one that best fits your needs.</p><h4>3. Bootstrap 4</h4><p>Today, when nearly all web apps need to look pretty whether they’re opened on a regular desktop or mobile device, you’re not going to have time to write all the necessary CSS code yourself to make that happen. There’s also many features in front-end web development that can enhance user experience such as popovers, popups, navigation bars, alerts, etc. If you try to implement these things yourself, it’s just going to result in a massive amount of boiler plate code that’s going to take forever to development and maintain. Bootstrap is a front-end library created by Twitter which provides a plethora of utilities. It includes a lot from styling to interactivity so you don’t have to write them all from scratch.</p><p>Of course you don’t have to know all of Bootstrap’s features right off the bat, but I highly recommend getting familiar grid layout and navigation bars before starting your first web app. They are pretty ubiquitous across the web and are vital to making your site mobile friendly. The two major front-end frameworks mentioned before (Angular and React) have libraries for integrating with Bootstrap, so you don’t have to worry about its features not being compatible within these frameworks.</p><h4>4. HTML/CSS</h4><p>Even though Bootstrap can carry a lot of your CSS weight for you, you’re still going to want apply your own custom styling and make slight modifications to whatever front-end libraries you may be using. Most of the things you need to do in CSS can be quickly googled for, but if you really want to spice up your site and have any kind of love for design like I do, you’ll need to have a pretty good understanding of CSS. This includes tasks like importing and styling custom fonts, setting properties based on screen width that Bootstrap grids might not be able to cover, and using CSS selectors like :nth-child(). As for HTML, there’s not much to learn right away and you can kind of learn as you go, but before making your first templates, know the difference between in-line elements like &lt;span&gt; and how they differ from block ones like &lt;div&gt;. This will save you a huge amount of headache when fiddling with your CSS code.</p><p>If you’re like me you might find HTML with its open/close tags and CSS with all of its selectors a little bloated. The good news is there are number of preprocessors out there which make these template languages may more fun and terse. For Html we have tools like Pug and HAML: HTML preprocessors aren’t used as much as CSS ones. For CSS there are a number of options such as Stylus, LESS, SASS, and PostCSS. Angular’s command line has plugins for a number of these built into it and there are separate plugins for React as well. I’m partial to Pug and Stylus because they’re so feature rich.</p><h4>5. NodeJS and a back-end framework</h4><p>NodeJS is the environment for running JavaScript on the back-end just like you would any other programming language. Of course being on the desktop there are going to be some slight differences from JavaScript in the browser. Both the browser and Node execute JavaScript and they both use the V8 engine. The primary difference is the browser adds an additional API to access the DOM, and Node adds an API to interact with the operating system. If you want to do full-stack JavaScript, you have to know NodeJS. Good news is you don’t have to learn a completely different language.</p><p>Just like the front-end, you have a number of options when choosing a back-end framework. ExpressJS is however kinda the de facto standard. Express makes it easy to spin a back-end web server and start writing APIs. If you want to play around with different back-end frameworks, I’d recommend starting off with Express and then experimenting once you got a feel for back-end JavaScript.</p><h4>6. Learn TypeScript</h4><p>JavaScript is so yesterday; it has countless issues. Cross browser compatibility, different versions of NodeJS, no type safety which makes scaling difficult, and only semi object-orientedness with ES6&#39;s class keyword. TypeScript transpiles to clean ES5 code which eliminates much of the compatibility problems. It also enables you to write JavaScript in a much more traditional object-oriented way similar to C#/Java.</p><p>Using TypeScript has made me a much better programmer and helped me understand concepts like interfaces, inheritance, access control (public, private, etc), and abstraction much better. If your background is OO like mine is, TypeScript will feel way more natural to you than regular JavaScript. Another useful point about TypeScript is it can be used with a lint file which enforces certain coding standards.</p><h4>7. Get familiar with an API calling tool</h4><p>A big mistake a lot of new full-stack developers tend to make, myself included, is they’ll trigger APIs from the front-end while developing the back-end. This will massively increase the time it takes to implement your server code. You’ll have to reenter your values every time the page is refreshed and navigate to the portion of the front-end where the APIs are called. To speed up this process you should develop your back-end and front-end separately. Get familiar with an API calling tool like <a href="https://www.getpostman.com/">Postman</a> or <a href="https://www.soapui.org/">SoapUI</a>, so you can call your APIs without having to touch the front. Know how to use them for authenticated routes as well you can make API calls without having to login to your app.</p><h4>8. Know some SQL</h4><p>Despite all the hype around NoSQL databases and the popularity of MongoDB among NodeJS developers, relational databases still tend to be the most practical choice for many applications. Regardless of whether or not you’re using JavaScript for the back-end, decent SQL knowledge should be a prerequisite for anyone who wants to call themselves a full-stack web developer. Just like JavaScript, you don’t need to be an expert, but to start off you should know how to do basic joins, create/update tables, and insert data.</p><p>Most of the major relational databases, notably MySQL and PostgreSQL, integrate nicely with NodeJS. You can talk to them just as easily as you would MongoDB or any other NoSQL database. Personally, I find that standard SQL queries tend to be a little more intuitive than some databases which query using JSONs (JavaScript objects). If you want to store your data as JSONs, guess what, PostgreSQL and MySQL still let you do that.</p><h4>9. Unit and End-to-End Testing</h4><p>Do not, I repeat do not underestimate the importance of testing. I’ve noticed in the real world there is a tendency to neglect unit-testing especially on the front-end. Testing will not only prevent bugs for the users but also make your code much more robust and force you to review it. Some frameworks like Angular have tools for testing built in so you don’t have to configure much; you can just start writing tests.</p><p>Any element on a web page whose behavior changes based on user interaction needs to be unit-tested. In the back-end, all routes and public methods which can be triggered by a user also need to be unit-tested. End-to-end testing (aka integration or e2e testing) should be done for any user interaction which spans multiple web pages and talks to the back-end. For example, logging in with a redirect would need to be e2e tested. If a user is redirected to lets say a profile page after successfully logging into their account, that needs to have an e2e test.</p><h4>10. Basics of User-Authentication</h4><p>There are a number of ways you could go about making your website secure: client-side tokens, session storage, handing off authentication to a third-party tool like MS Active Directory. You don’t need to know them all, but you should have an idea of what’s available. Once you do, pick the option that is easiest and build up your knowledge from there. Also, get a general idea of the major forms of attack that hackers can use against your website. You don’t need be an internet security expert, but know the main ones so your site isn’t susceptible. This would include things like cross-site scripting requests and SQL injection attacks. There’s a good article <a href="https://www.creativebloq.com/web-design/website-security-tips-protect-your-site-7122853">here</a> which covers some of the basics of internet security.</p><p>For securing the APIs in your back-end, I recommend starting off with JSON web tokens (JWT). NodeJS has some great third party libraries for using them with Express and they’re pretty easy to work with. JWTs are a form of client-side authentication which you can use to only allow valid users (i.e. those who have logged in) to make requests to your back-end. JWTs can also store encrypted JSON objects so you can identify who is making the secured request. If you want to create persistent information for users (i.e. storing a shopping cart for a user when they leave the site), you’ll eventually need to learn about sessions.</p><p>How do you feel about this list? Feel free to post any comments if you think something is missing or not needed. Keep in mind the JavaScript world is huge so there is a lot to cover, but these were the topics I needed to teach myself when making my first website. Even if you’re a new web developer and not sure you’ll end up using full-stack JavaScript in the future, knowing most these skills will make you a more productive well-rounded coder.</p><p>P.S. If you’re interested in using back-end TypeScript with ExpressJS, please checkout my library OvernightJS which adds decorators to express routes. Here’s a <a href="https://levelup.gitconnected.com/overnightjs-the-best-way-to-use-expressjs-with-typescript-35d71941aade">link</a> to a Medium article which describes how to use it.</p><p>Happy web-deving :)</p><figure><a href="https://levelup.gitconnected.com/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9uYu-fFL3hIQLGVu0o-EQ.png" /></a></figure><p><a href="https://gitconnected.com/learn/javascript">Learn JavaScript - Best JavaScript Tutorials (2019) | gitconnected</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b76467711ac" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/10-things-to-learn-for-becoming-a-solid-full-stack-javascript-developer-8b76467711ac">10 things to learn for becoming a solid full-stack JavaScript developer</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OvernightJS: The best way to use ExpressJS with TypeScript]]></title>
            <link>https://levelup.gitconnected.com/overnightjs-the-best-way-to-use-expressjs-with-typescript-35d71941aade?source=rss-2b1b1f90d011------2</link>
            <guid isPermaLink="false">https://medium.com/p/35d71941aade</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[overnightjs]]></category>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Sean Maxwell]]></dc:creator>
            <pubDate>Sun, 16 Sep 2018 03:58:30 GMT</pubDate>
            <atom:updated>2019-01-27T21:26:42.031Z</atom:updated>
            <content:encoded><![CDATA[<p>TypeScript decorators for the ExpressJS web framework</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*qxSjwDKjdFRB1qpKV1Tilg.png" /><figcaption>Overnight is faster than Express, get it?</figcaption></figure><h3>OvernightJS Introduction</h3><p><a href="https://github.com/seanpmaxwell/overnight">OvernightJS</a> is a simple library to add TypeScript decorators to ExpressJS routes. It’s not meant to act as an extra layer on top of Express or take you away from the RESTful style of writing back-end web APIs. There are some complex libraries out there which do add TypeScript decorators to Express but they are practically brand new frameworks with huge amounts of documentation. OvernightJS is simple, easy and hardly takes any time to learn if you are already somewhat familiar with ExpressJs.</p><h3>How it works</h3><p>Once you’ve installed OvernightJS, simply import the controller decorator, place it right before a TypeScript class, and pass it a route (as a string). This string will be prepended to all method routes in your controller. You may add routes to the controller by using decorators for Express GET, POST, PUT, and DELETE routes. Your method will work exactly the same as if it were placed inside of an Express route callback method. The decorators support ExpressJS middleware as well. Any middleware you’d normally pass as the second argument to an express route, simply pass it as the second argument to the decorator.</p><p>So instead of doing this…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2a599f3c6abc29d26c0868e0791d648/href">https://medium.com/media/e2a599f3c6abc29d26c0868e0791d648/href</a></iframe><p>You can do this :)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcef9f8be84254c015e0067afe7f8207/href">https://medium.com/media/bcef9f8be84254c015e0067afe7f8207/href</a></iframe><p>Once you start amassing large numbers of controllers and methods, this will save you a lot of code. What do you say we get started?</p><h3>Installation</h3><pre>$ npm install --save @overnightjs/core express</pre><pre>$ npm install --save-dev @types/express</pre><h3>Tutorial</h3><p>After you install OvernightJS, import the “Controller<em>”</em> decorator at the top of your TypeScript file and any decorators you want to use for your API routes. If you want to use async/await, guess what? Those work just fine. The ‘next’ parameter is also optional. Here I’m trying to show you as many different examples as I can of different routes being used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44f158aa2cb90e5bc7346a5ead009679/href">https://medium.com/media/44f158aa2cb90e5bc7346a5ead009679/href</a></iframe><p>Once you’ve set up your controller, import it at the top of your server file. The ‘Server’ parent class, which is part of the @overnightjs/core package, is necessary to enable the routes. This parent class also gives us an ExpressJS instance which we can interact with normally just like any other express instance. Routes are initialized using the “addControllers()” method seen on line 18 below. This method can be passed a single controller or an array of controllers.</p><p>Another cool feature of this library is you’re not required to use the built-in express.Router() object. A custom library of your choice can be added by passing it as the second argument to the “addControllers()” method. If you don’t specify a Router object, the default express.Router() one is used. The code snippet below contains 2 different examples of “addControllers()” being used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bc00f5e131451943a0da4b233d778ac/href">https://medium.com/media/3bc00f5e131451943a0da4b233d778ac/href</a></iframe><p>That’s all there is to it. Pretty easy right? The main GitHub repository (link below) contains a sample application if you want to see OvernightJS in action.</p><h3><strong>Links</strong></h3><ul><li><a href="https://github.com/seanpmaxwell/overnight">seanpmaxwell/overnight</a></li><li><a href="https://www.npmjs.com/package/@overnightjs/core">@overnightjs/core</a></li></ul><figure><a href="https://levelup.gitconnected.com/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8lHUzxrIT5VDhu7fUS6gg.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35d71941aade" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/overnightjs-the-best-way-to-use-expressjs-with-typescript-35d71941aade">OvernightJS: The best way to use ExpressJS with TypeScript</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>