Enrolled to Infinite Learning

Wednesday 2 December 2020

TypeScript for Frontend And Backend Developers

 

What to Expect from this Post?

If you are a Javascript developer, or work on any other UI framework/ library, or have an understanding of any of them, this post is for you. This post primarily covers those features of Typescript which are beyond Javascript's capabilities. The only prerequisite for you to learn typescript is basic knowledge of Javascript and fair understanding on OOPs paradigm.


What is TypeScript?


By definition, “TypeScript is JavaScript for application-scale development.”

TypeScript is a strongly typed, object oriented, compiled language. TypeScript is a typed superset of JavaScript compiled to JavaScript. In other words, TypeScript is JavaScript plus some additional features.

The TypeScript compiler (tsc) converts the instructions written in TypeScript to its JavaScript equivalent.

This helps backend developers write front-end code faster. Angular 2+ also utilizes typescript.


Features of TypeScript


TypeScript is just JavaScript. TypeScript starts with JavaScript and ends with JavaScript. Typescript adopts the basic building blocks of your program from JavaScript. Hence, you only need to know JavaScript to use TypeScript. All TypeScript code is converted into its JavaScript equivalent for the purpose of execution.

TypeScript supports other JS libraries. Compiled TypeScript can be consumed from any JavaScript code. TypeScript-generated JavaScript can reuse all of the existing JavaScript frameworks, tools, and libraries.

JavaScript is TypeScript. This means that any valid .js file can be renamed to .ts and compiled with other TypeScript files.

TypeScript is portable. TypeScript is portable across browsers, devices, and operating systems. It can run on any environment that JavaScript runs on. Unlike its counterparts, TypeScript doesn’t need a dedicated VM or a specific runtime environment to execute.

Compilation −TypeScript will compile the code and generate compilation errors, if it finds some sort of syntax errors. This helps to highlight errors before the script is run.

Strong Static Typing − JavaScript is not strongly typed. TypeScript comes with an optional static typing and type inference system through the TLS (TypeScript Language Service).

TypeScript supports Object Oriented Programming concepts like classes, interfaces, inheritance, etc.

ES 6 Features- TypeScript includes most features of planned ECMAScript 2015 (ES 6, 7) such as class, interface, Arrow functions, etc.

Better IDE support- The development experience with TypeScript is a great improvement over JavaScript. There is a wide range of IDEs that have excellent support for TypeScript, like Visual Studio & VS code, Atom, Sublime, and IntelliJ/WebStorm.

Strict Null Checking- Errors, like cannot read property ‘x’ of undefined, is common in JavaScript programming. You can avoid most of these kinds of errors since one cannot use a variable that is not known to the TypeScript compiler.


TypeScript vs JavaScript




JavaScript

TypeScript

LanguageScripting languageObject-oriented programming language
Learning CurveFlexible and easy to learna programmer should have prior scripting knowledge
TypeLightweight, interpreted programming languageStrongly type object-oriented programming language
Client/Server sideBoth client and server-sideSpecially used in client-side
File Extension.js. ts or .tsx
TimeFasterTakes time to compile the code
Data BindingNo concept of types and interfaces availableConcepts like types and interfaces used to describe the data being used.
AnnotationsAnnotations not requiredCode must be annotated constantly to get the most out of TypeScript Features.
SyntaxAll the statements are written within the Script tag.
The browser program starts interpreting all the text between these tags as a script<script>// javascript code</script>
A TypeScript program is composed of:
Modules
Functions
Variables
Statements
Expressions
Comments
Static TypingThere is no concept of Static typing in JavaScriptSupports static typing.
Support for ModulesDoes not support modulesGives support for modules
InterfaceDoes not have an interfaceHas an interface
Optional parameter functionDoes not supportSupports
Prototyping FeatureDoes not have any such featureHas a feature of prototyping
Community of developersAs JavaScript occupies the major chunk of codes, it is widely accepted and used by the programming communityTypeScript is new and has a relatively smaller community base.
Preference to chooseJavaScript is preferable to use in small coding projects.TypeScript is an object-oriented language which makes the code more consistent, clean, simple and reusable. So it is better to use TypeScript for large projects.


How Typescript Works?



TS code->

var num:number = 12;

var str:string = “Hello”;

var alphas:string[];

alphas = ["1","2","3","4"];

On compiling, it will generate the following JavaScript code.

var num = 12;

var str = “Hello”;

var alphas;

alphas = ["1", "2", "3", "4"];

var nums= [1,2,3,3];


How to Install TypeScript?


There are two main ways to install TypeScript tools such as:

  1. Via npm (Node.js Package Manager) command-line tool
    npm install -g typescript
  2. By installing TypeScript via Visual Studio.


Compile and Execute a TypeScript Program


1)    Save the file with .ts extension.

2)    To compile the file use the following command on the terminal window.

     tsc app.ts

3)    The file is compiled to Test.js. To run the program written, type the following in the terminal.

     node app.js

The TSC generates a JavaScript version of the .ts file passed to it. In other words, the TSC produces an equivalent JavaScript source code from the Typescript file given as an input to it. This process is termed as transpilation.


DataTypes


The Type System in Typescript checks the validity of the supplied values, before they are stored or manipulated by the program. This ensures that the code behaves as expected. It has both, in-built and user-defined data types.


TypeScript Interfaces


Another interesting feature of typescript is its support for interfaces.

An interface is a syntactical contract that an entity should conform to. In other words, an interface defines the syntax that any entity must adhere to.

Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow.

Let’s consider an object −

var person = {

   FirstName:"Tom", 
   LastName:"Hanks", 
   sayHi: ()=>{ return "Hi"} 
};

If we consider the signature of the object, it could be −

{ 
   FirstName:string, 
   LastName:string, 
   sayHi()=>string 
}

To reuse the signature across objects we can define it as an interface.

Example: Interface and Objects


interface IPerson {

   firstName:string,

   lastName:string,

   sayHi: ()=>string

}

var customer:IPerson = { 
   firstName:"Tom",
   lastName:"Hanks", 
   sayHi: ():string =>{return "Hi there"} 
} 


The customer object in the example is of the type IPerson.

Interfaces can also be inherited by other interfaces.


Optional Parameters And Default Parameters


Optional parameters can be used when arguments need not be compulsorily passed for a function’s execution.

// Optional Parameters
sayHello(hello?: string) {
    console.log(hello);
}

sayHello(); // Prints 'undefined'

sayHello('world'); // Prints 'world'


Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values.

// Default Parameters
sayHello(hello: string = 'hello') {
    console.log(hello);
}

sayHello(); // Prints 'hello'

sayHello('world'); // Prints 'world'


Typescript Classes


Typescript is Object Oriented Javascript. It supports classes, with a simple syntax like-

class class_name {

   //class scope

}

A class definition can include constructors, fields, functions.

Example:

class Test {

   //field

   projectName:string;

   //constructor

   constructor(projectName:string) {

      this.projectName = projectName;

   }

   //function

   disp():void {

      console.log("Project Name is  :   "+this.projectName)

   }

}

//creating object

var obj = new Test("Test Automation")


//access the field

console.log("Reading attribute value Project Name as :  "+obj.projectName)


//access the function

obj.disp()


The class Test has a field projectName, of type string, and a method that returns nothing (void). Obj is the class object.

The concept of class inheritance is also supported in Typescript. Syntactically, extends keyword is used for inheritance. Rest of the method remains similar to Javascript.

Syntax-

class child_class_name extends parent_class_name


Other OOPs concepts like method overloading, encapsulation, data hiding are also supported by Typescript.


Classes and Interfaces



Classes can also implement interfaces.

interface ILoan {

   interest:number

}

class AgriLoan implements ILoan {

   interest:number

   rebate:number

   constructor(interest:number,rebate:number) {

      this.interest = interest

      this.rebate = rebate

   }

}

var obj = new AgriLoan(10,1)

console.log("Interest is : "+obj.interest+" Rebate is : "+obj.rebate );


The class AgriLoan implements the interface Loan. Hence, it is now binding on the class to include the property interest as its member.


Namespace


A namespace is a way to logically group related code. This is inbuilt into TypeScript unlike in JavaScript where variables declarations go into a global scope and if multiple JavaScript files are used within same project there will be possibility of overwriting or misconstruing the same variables, which will lead to the “global namespace pollution problem” in JavaScript.


Defining a Namespace


A namespace definition begins with the keyword namespace followed by the namespace name as follows −

namespace SomeNameSpaceName { 
   export interface ISomeInterfaceName {      }  
   export class SomeClassName {      }  
} 

The classes or interfaces which should be accessed outside the namespace should be marked with keyword export.


Modules


Typescript modules are divided into two categories- Internal and External modules.

Internal Modules are logically grouped classes, interfaces, functions into one unit and can be exported in another module. This logical grouping is named namespace in latest version of TypeScript.

Syntax:

namespace TestModule {

  export function add(x, y) { console.log(x + y);}

}


External modules in TypeScript exist to specify and load dependencies between multiple external js files.

There are two scenarios for loading dependents js files from a single main JavaScript file.

  • Client Side - RequireJs
  • Server Side - NodeJs


Syntax-

Exporting:

//FileName : SomeInterface.ts

export interface SomeInterface {

  //code declarations

}

Importing:

import someInterfaceRef = require(“./SomeInterface”);


End Note


Programmers coming from Object Oriented world will find it easy to use TypeScript. With the knowledge of TypeScript, they can build web applications much faster, as TypeScript has good tooling support.

Friday 18 September 2020

Frontend Development Essentials

Oftentimes people ask me on where to start with to become a frontend developer. I generally give them an overview and suggest to befriend Google. But what I figured out lately is that Google apparently overwhelms you with tons of results for each keyword and confuses you more than educating! This post is a broader level roadmap and assistance on the same note. UI development is an ocean, this one is just a drop near the shore. 

Basic Pillars of Frontend Development-

HTML 

Hyper Text Markup Language (HTML) is a markup language that allows you to structure the information that is displayed to the user. Its the An HTML document consists of elements each represented by an HTML tag, such as a heading, a paragraph of text or a text input field. HTML documents can also link to other documents using hyperlinks. Each tag carries its own type of content, has a certain appearance and attached behavior.

CSS

Cascading Style Sheets (CSS) is a styling language used to describe the visual appearance of HTML elements. It can be used to controls aspects like the positioning of an element, its dimensions, text style or colors, or almost any other visual aspect of a website. Styles are defined as a set of rules that can be applied to a single element of a subset of elements on the page.

Preprocessors

Preprocessors extend the capability of CSS to make your CSS code base simpler and maintainable. Various preprocessors like SASS/SCSS, LESS, PostCSS can be leveraged for this purpose.

Javascript

JavaScript (JS) is the most used programming language for developing user interfaces for the web. It allows you to add custom behavior to your websites, such as reacting to user events, loading data from web services and showing or hiding elements on a page. It also allows you to interact with the browser through various APIs. You can use it to both add separate interactive elements to your website or create complex web applications.

Plethora of Tools

PACKAGE MANAGER- NPM

TASK RUNNERS- Webpack, Grunt, Gulp

ONLINE CODING ENVIRONMENTS- StackBlitz, CodePen, JSBin

CODE EDITORS – Atom, Visual Studio Code, Webstorm

FRONT-END ASSETS- Google fonts, FontAwesome, Unsplash

DEVELOPER TOOLS- Chrome Dev Tools, Firefox Page Inspector, Microsoft Edge Developer Tools and Safari Web Inspector

CODE LINTING- ESLint, JSLint, CSS Lint

Modern Frontend Libraries

React  is a user interface development library developed by Facebook. React is based around creating components, such as a button or a side menu, that can render HTML based on input parameters. React components are written using an extension to JavaScript called JSX, that allows you to conveniently combine JavaScript code and HTML. Components can be composed together to create complex UI elements and whole applications. React is not a framework per se, it only provides the view layer, however, its rich ecosystem of tools and libraries.

Angular is another JS framework for developing user interfaces. It is developed by Google, based on typescript, and is component oriented. It provides most of the things you’ll need to build a web application including a CLI tool to bootstrap, develop and build the project as well as libraries to manage forms, data loading, routing, etc.

Vue.js is a framework designed to be modular and incrementally adoptable. You can start using it as a view layer and add additional libraries as you need them.

General Best Practices

Modern Javascript frameworks are evolving quickly to meet the high-end needs of user experience and upgraded development environments. Yet, to leverage them at their maximum potential, one needs to follow a set of standard practices.

1. Clean Code 

Clean code should be elegant and pleasing to read. It should be focused, and you should take care of it. All tests are run in clean code. They shouldn’t contain duplications, and the use of entities, such as classes, methods, and function, should be minimized.

2. Keep your code organized

We need a directory structure that will make it easy to

•         add things as we go,

•         keep the size of our modules manageable,

•         And keep everything in an easy-to-navigate, logical structure.

3. Simplicity

Any software should be created in the most efficient way without unnecessary complexity. Simpler answers are usually more correct, and this thought perfectly meets the needs of the development process. Simplicity coincides with minor coding principles such as Don’t Repeat Yourself (DRY) or You Aren’t Gonna Need It

4. Consistency helps a lot because colleagues will be able to test, edit or continue the work of each other. Vice versa, inharmonious projects can confuse your team and slow down the development process. Here are some tools that will help you enforce a single style:

-> Editorconfig: A system for the unification of code written with different IDEs,

-> ESLint: A highly customizable linter based on node.js,

-> HTML Tidy: Another linter for HTML which also finds errors and;

              -> Stylelint: A linter for CSS with various plugins.

-> Pre-commit hooks- They ensure code isn’t committed unless it meets certain requirements like, linting, testing, commit message of a particular format etc.

5. Accuracy over speed: Focus on correct code instead of fast code. Later it will be easier to speed up processes than rewrite everything and;

6. Experience sharing: Consider exchanging ideas and results with other developers to get external reviews if your project isn’t confidential.

7. Testing

No untested code should find it’s way to production. It’s better for any developer to integrate tests in the development workflow whenever possible.

One can differentiate between test cases like:

a. Unit tests

Testing a single component or function in isolation.

b. Integration tests

Testing interactions between components.

c. End-to-end test

Testing full-blown user flows in the browser.

8. Defining a highly scalable folder structure 

Defining a highly scalable folder structure is recommended  when you aim to build a scalable Angular app. I would suggest you practice a folder structure that is fit for all real-world examples with progressive addition of cases with time if not at the initial phase.

9. Checklist

Maintain a checklist to test the following-

a. Typography- Ensure that the UI matches the prototype. The visual correspondence, the position of the elements, and the distance between them should be similar to those designated in the wireframe. The text should be correct and have no grammatical errors, based on wireframes.

b. Style conformity – Conforming to the brand colors, styles etc. The graphical objects to be used appropriately and according to the guidelines specified in Graphical User Interface Design.

c. Adaptability- Check how it is displayed on all the supported browsers, devices and operating systems.

d. The functionality use- The button clicks, hyperlinks, navigation and other controls to match the needs.

e. Messaging- Look for info, warning and error messaging appropriately, and on what event the feedback is expected to be displayed.

f. Internationalization- Provide for extensibility to support internationalization in the application.


10. Code Linting- Integrate JSLint/ ESLint/ TSLint, CSS Lint with the IDE to ensure uniformity of code.

11. Naming conventions- Follow appropriate naming conventions for the JS/TS, CSS, HTML files and maintain uniform naming style.

12. Coding Style- 


a. Code Commenting- Add comments wherever needed.

b. No hardcoded values, use constants values.

c. Avoid multiple if/else blocks.

d. No commented out code.

e. No unnecessary comments: comments that describe the how.

f. Add necessary comments where needed. Necessary comments are comments that describe the why.

g. Keep components small.

h. Code should have no linting errors.

i. No console logs

j. Avoid inline styles.

k. CSS selectors are only as specific as they need to be, grouped logically.

l. Use Hex codes (#000) in css.


13. Make sure no dist files, editor/IDE files, etc are checked in. There should be a .gitignore for that.

14. Ensure usability of the application from the end user’s perspective, and suggest necessary UX updates.

15. Tests are readable, maintainable, trustworthy.




Let us change our traditional attitude to the construction of programs. Instead of imagining that our main task is to instruct a computer what to to, let us concentrate rather on explaining to human beings what we want a computer to do.
--Donald Knuth

Categories

Agile (1) Angular JS (2) CSS (1) css reset (1) Grunt (1) Jasmine (1) Karma (1) Scrum (1) setup (1) Sprint (1) test cases (1) Typescript (1) UI Automation (1) Webstorm (1)
Disclaimer

The information and images of this blog are sometimes referred from various websites and blogs across the web to provide the best possible content to the reader. The information furnished hereby cannot be used for legal purposes. I will not be liable to you (whether under the law of contact, the law of torts or otherwise) in relation to the contents of, or use of, or otherwise in connection with, this website.