TypeScript Basics - A Definitive Guide
Tags: showdev, webdev, typescript, javascript
Published: 2019-10-20 13:23:18

---
title: TypeScript Basics - A Definitive Guide
published: true
description: TypeScript Basics - A Definitive Guide
tags: showdev,webdev,typescript,javascript
cover_image : https://am22.akamaized.net/tms/cnt/uploads/2019/08/he-man-netflix-series-1200x750.jpg
canonical_url: https://cloudnweb.dev/2019/10/typescript-basics-a-definitive-guide/
---
<!-- wp:paragraph -->
<p>In this article, we will learn some basics of typescript which helps you to develop javascript application in a better way. TypeScript Basics - A Definitive Guide</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>What is TypeScript and why we need it?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>So, before diving into the concepts of typescript. we should know what is typescript and why it is needed. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Firstly, TypeScript  is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors&nbsp;<em>as you type the code</em>. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>As a Javascript developer, there is one thing that we miss  when compared with other languages such as Java,C#. that is, <strong>TypeCheck</strong>. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>languages like java checks the type of defined variable in the compile time itself unlike javascript. it helps to solve lot of bugs in the compile time itself</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To solve this problem in javascript. <a href="https://medium.com/tech-tajawal/typescript-why-should-one-use-it-a539faa92010">TypeScript </a>is introduced.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Setting up TypeScript</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>TypeScript is only for development purpose. Since, browser/JS engine doesn't understand anything except javascript. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>So, we need to compile the typescript to javascript before running it the server/browser.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here's an <a href="https://cloudnweb.dev/2019/09/building-a-production-ready-node-js-app-with-typescript-and-docker/">article </a>explaining the complete setup and production deployment of typescript in Node.js Application.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Understanding Types</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Types are not a new in javascript. javascript already have dynamic types. they are,</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Undefined </li><li>Null</li><li>Boolean</li><li>Number</li><li>String</li><li>Symbol</li><li>Object</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>But, these types in javascript are dynamic. javascript checks the type of variables in run time. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Instead of checking the type in runtime, Typescript check that on compile time. static type predicts the value of dynamic types.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Basic Static Types</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>String</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>it is a textual data surrounded by single or double quotes</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const message: string = 'hello world';
console.log(message);</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":4} -->
<h4>Boolean</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>this type represents the boolean value which is either true or false</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const isType: boolean = false
console.log(isType);</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":4} -->
<h4>Number</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>this type represents the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Numbers">integer </a>value in the variable. there are four type of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Numbers">number literals</a> supported in the number type</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const age: number = 40;
console.log(age)</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":4} -->
<h4>Array</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>there are two ways to type check an array in Typescript. first way is to add <strong>[]</strong> to the element type</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>let newArray: string[] = ["one", "two", "three"]
console.log(newArray)</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>second way is to use the keyword Array with the type,</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>let newArray: Array&lt;string> = ["one", "two", "three"]
console.log(newArray)</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":4} -->
<h4>Enum</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p> enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Mainly, there are three types of enum,</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Numeric Enum</li><li>String Enum</li><li>Heterogenous Enum</li></ul>
<!-- /wp:list -->

<!-- wp:code -->
<pre class="wp-block-code"><code>enum Status {
    Inactive = 0,
    active = 1
}

console.log(Status.active)</code></pre>
<!-- /wp:code -->

<!-- wp:code -->
<pre class="wp-block-code"><code>enum Status {
    Inactive = "INACTIVE",
    active = "ACTIVE"
}

console.log(Status.active)</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":4} -->
<h4>Any</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>if the variable type is not known and we don't want the type checker for the particular variable, then the type of <strong>any </strong>can be used.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>let checkValue: any = true

checkValue = "Check";
checkValue = 14</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":4} -->
<h4>void</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>void is used when there is no return value in the function. if there is no return data type for a function, void is used.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const LogIt = (): void => {
    console.log("log")
}</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":3} -->
<h3>Type Inference</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Mainly, TypeScript has a feature which identifies the type of variable from the value assigned to it. it is called<strong> Type Inference</strong>. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For example, </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>let userName = "String"</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>TypeScript identifies the variable userName as a string from it's value. and throw error if you assign a type number to it.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This concept is called as Type Inference.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Interface</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Firstly, interface in Typescript is a way to check the type of an object. if we  want to check the type of values in group. Interface is the best choice.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For Example,</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>interface userData {
    name: string,
    age : number
}

let AddUserDetails = ({ name, age }: userData): void => {
    let arr = [];

    arr.push({
        name,
        age
    })
}

AddUserDetails({ name : "Ganesh",age : 25});</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Here, we have a function called <strong>AddUserDetails </strong> which takes two arguments such as <strong>name</strong> and <strong>age</strong>. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To check the Type of Both arguments, we need interface. So, we created an interface <strong>userData </strong>and typecheck it.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>if we pass first value as number, it will throw an error. Alternatively, we can define type of <strong>any </strong>to pass value.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Generics</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p> In TypeScript, Generics enables you to create reusable code components that work with a number of types instead of a single type. For Example,</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>
const createNewArray = (value: string): Array&lt;string> => {
    let output : Array&lt;string> = [];

    output.push(value);

    return output;
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Here, function <strong>createNewArray</strong> takes an argument with type <strong>string </strong>and return an array with that value. but what if we want to create an array with type <strong>number</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:html -->
<iframe height="400px" width="100%" src="https://repl.it/@ganeshmani/generictypescript?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe>
<!-- /wp:html -->

<!-- wp:paragraph -->
<p>above implementation with throw an compilation error on that scenario. we can solve this problem using <strong>Generic</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>
const createNewArray = &lt;T>(value: T): Array&lt;T> => {
    let output : Array&lt;T> = [];

    output.push(value);

    return output;
}

let val = createNewArray&lt;string>("fdfsd");

console.log(val)</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>The above example has a generic type T that corresponds to the type of the argument that is passed to the <strong>createNewArray </strong>function. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>T is a naming convention that represents string here, because we are passing Type <strong>string </strong>while we call the function. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If we change the type to number while we call function/class. it will take the type dynamically. that's the beauty of <a href="https://medium.com/@rossbulat/typescript-generics-explained-15c6493b510f">Generics</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>there are different way to implement the generics, we can implment it in Interface, Class and Type Generics.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Conclusion</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Honestly, we barely scratched the surface of TypeScript. we will see this concepts in more depth in upcoming articles, until then you can refer some wonderful articles on typescript.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://www.typescriptlang.org/docs/handbook/basic-types.html">TypeScript Handbook (Official TypeScript docs)</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://basarat.gitbooks.io/typescript/content/docs/getting-started.html">TypeScript Deep Dive (Online TypeScript Guide)</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="http://2ality.com/2018/04/type-notation-typescript.html">Understanding TypeScript’s Type Annotation (Great introductory TypeScript article)</a></p>
<!-- /wp:paragraph -->