This document provides an introduction to TypeScript, a superset of JavaScript that adds optional static types and classes. It discusses why TypeScript was created due to issues with maintaining large JavaScript codebases. The document then covers TypeScript features like type checking, classes, interfaces, modules, and how it compiles to JavaScript. It provides examples of TypeScript syntax for types, classes, interfaces, and other language features. Overall, the document serves as an introduction to TypeScript for developers familiar with JavaScript.
2. 2
TYPESCRIPTTYPESCRIPT
Contents
Introduction............................................................................................................................................................. 3
What is this e-book for?........................................................................................................................................ 3
What is TypeScript?................................................................................................................................................ 4
Typescript Installation........................................................................................................................................... 4
Why Typescript?...................................................................................................................................................... 4
Types in TS............................................................................................................................................................... 5
Support to duck typing.......................................................................................................................................... 5
Use of Jquery in TS................................................................................................................................................. 6
Handling Undefined .............................................................................................................................................. 6
This Keyword........................................................................................................................................................... 6
Creation of classes................................................................................................................................................. 7
Single Inheritance in TypeScript.......................................................................................................................... 7
Static Keyword......................................................................................................................................................... 7
Access modifiers..................................................................................................................................................... 8
Abstract keyword.................................................................................................................................................... 8
Property Initializer (ES 7 feature)........................................................................................................................ 8
Super keyword........................................................................................................................................................ 8
Arrow functions....................................................................................................................................................... 9
Inheritance & this keyword.................................................................................................................................. 9
Rest parameters..................................................................................................................................................... 9
Let keyword.............................................................................................................................................................. 9
Const keyword......................................................................................................................................................... 9
Deep Immutability in TypeScript......................................................................................................................... 10
Destructuring in TypeScript................................................................................................................................. 10
Array destructuring................................................................................................................................................ 10
Array destructuring with rest............................................................................................................................... 10
Array destructuring with ignores........................................................................................................................ 11
Forโฆ.Of keyword..................................................................................................................................................... 11
Template Strings .................................................................................................................................................... 11
Spread operator..................................................................................................................................................... 12
Promise..................................................................................................................................................................... 12
Creating a promise................................................................................................................................................. 12
Tip............................................................................................................................................................................... 12
Chainability of promise......................................................................................................................................... 13
Best practices ......................................................................................................................................................... 13
Conclusion................................................................................................................................................................ 13
3. 3
TYPESCRIPT
Introduction
Ever Since web browsers and internet was a part of our civilisation, Javascript ruled the part of adding interactions
to our web applications/web sites. Over the years, as days pass by, Javascript (nick-named โJSโ) became versatile.
With technologies like NodeJS, ElectronJS and third party component integrations from Facebook, twitter and so
on, JS now stands tall. NodeJS calls itself server side javascript, that means we develop server side scalable network
components/ web apis with javascript. It never stops there, JS is now distributable. We use Facebookโs share icon by
integrating their JS library along with some custom html tags. JS is now used to build large-scale applications today.
When we say large-scale applications, there are concepts like reusability and maintainability concern us. JS still is
interpreted, not compiled language. ECMAScript is the subset of Javascript. ECMAScript updates its standards for
new user experiences. ECMAScript 5 and above has lots of new features introduced. Javascript tries to adapt to the
latest standards from ECMAScript but that now takes time. A team of engineers at Microsoft understood some of the
maintainability and scalability issues with Javascript and would like to resolve it by introducing Typescript.
Typescript is not a replacement for Javascript but is a superset of Javascript. The code that was built with JS will run
in Typescript too. Typescript is written following ES6 and above features. We will describe what it is in the following
pages.
What is this e-book for?
We saw an increase in the open-source community on Typescript usage. Some of the worldโs famous open source js
libraries now use Typescript. One of the finest examples is the protobuf.js library (https://github.com/dcodeIO/pro-
tobuf.js). It is the next generation to our rest apis designed at Google for faster data access without JSON. Angular
recommends typescript for its developers with its latest versions. There are more TypeScript repositories in github
on search than Javascript (April 01,2018).
Typescript
ES6
ES5
โข types
โข annotations
โข classes
โข modules
4. 4
TYPESCRIPT
(screen grab of repositories in github from url https://github.com/search?utf8=%E2%9C%93&q=typescript)
This e-book neither advocates JS lovers to convert to TS nor TS lovers to feel superior. Softcrylic uses TypeScript in
AutomateOn and tried for some components of TapestryKPI. I would like to recommend you love this new standard
of writing Javascript code. Below are some of the new items in TypeScript that makes this โnew programming lan-
guageโ interesting.
What is TypeScript?
TypeScript, simply, is a programming language, but not to replace Javascript. It is written based on ECMAScript stan-
dards 5 and above, calling it a superset of TypeScript.
Typescript compiles into JavaScript. In order to execute it, we need to have a
a. Typescript compiler,
a. Typescript editor (VS Code, Visual Studio 2013 updated and above, sublime text, atom or any editor of your
choice)
a. To install typescript compiler, we can use npm/sublime plugin and so on
Typescript Installation
We can run typescript either on a browser or a server.
Typescript is available in npm and can be downloaded by this command globally in your system
For OSX it has to be
Why Typescript?
a. JS never had variable types
The above syntax works, but in large systems, if we perform any operations on data, the output differs.
5. 5
TYPESCRIPT
Typescript checks types at compile time. It identifies type mismatch early.
Provides classes and module to follow an object-oriented standard for projects that are highly scalable. When we
deal with multiple codebases, typescript helps a lot.
Types in TS
TypeScript supports the following data types
a. Boolean -> var status:Boolean = false;
b. Number -> var a:number=123;
c. String -> var s:string=โ123โ;
d. Array -> var list:number[] =[1,2,3];
e. Enum -> enum Color{Red, Green, Blue};
f. Any -> var notSure:any;notSure=123;notsure=โ456โ;
g. Void -> function Do Something:void(){}
Even if data type is not specified it assigns a data type based on the values we assign
Support to duck typing
In JS, types are structural and hence duck typing is accepted. We can pass additional parameters as types and it is all
right.
6. 6
TYPESCRIPT
Use of Jquery in TS
Consider the jquery code we will use for a selector.
The above line of code will throw error saying $ is not defined while Jquery file is not referenced in JS. In TypeScript $
throws error when not declared. We have to try
Or
Protects you from portion of JS that never worked
Handling Undefined
It is important for us to check a property or a variable undefined or null in strict mode. If you used component based
frameworks strict mode is mandatory & automatically added.
This Keyword
The keyword โthisโ is called a calling context
//return the foo method instance
7. 7
TYPESCRIPT
Creation of classes
Classes provide structural abstraction.
Single Inheritance in TypeScript
TS supports single inheritance using the extends keyword.
Static Keyword
TS introduces static keywords that can be used on classes.
8. 8
TYPESCRIPT
Access modifiers
Accessible on Public Protected Private
Class Yes Yes Yes
Class children Yes Yes No
Class instances Yes No No
Abstract keyword
Property Initializer (ES 7 feature)
Super keyword
Used to initialize an object in the base class method.
9. 9
TYPESCRIPT
Arrow functions
๏ is thin arrow.
๏จ Is fat arrow functions (used) or lambda functions
Inheritance & this keyword
We canโt use โsuperโ keyword without โthisโ keyword. You can create a copy & use it.
Rest parameters
Rest parameters (denoted by โฆ..argument Name for last argument) allow you to quickly accept multiple arguments
in your function and get them as an array.
Let keyword
Var keyword in JS is function scoped.
This is why ES6 introduces โletโ keyword
Use let if you want a variable to be block scoped loop failures.
Const keyword
๏จ Declare constant with โconstโ keyword.
๏จ Must be initialized during declaration
10. 10
TYPESCRIPT
Block scoped
Deep Immutability in TypeScript
Destructuring in TypeScript
Breaking up the structure
Object destructuring Array destructuring
If assign an extended variable to a new variable name you can do the following.
Array destructuring
Array destructuring with rest
11. 11
TYPESCRIPT
Array destructuring with ignores
Forโฆ.Of keyword
Disadvantages of for in
Forโฆof exists in TS (ES6)
Template Strings
Syntactically these are strings that use backticks (i.e.) instead of angle (โ) or double (โ) quotes.
a. String interpolation
b. Multiline Strings
c. Tagged templates.
12. 12
TYPESCRIPT
Spread operator
Main objective is to spread the objects of an array.
In JS we had to us function.prototype.apply()
Promise
Modern JS engines have this and easily polyfilled.
The main motivation behind promises is to bring synchronous style and error handling to Async/Callback style code.
When we are using a callback it should follow the below rules while in call back.
a. Never call the callback twice
b. Never throw an error
Creating a promise
A promise can be either
a. Pending,
b. Resolved,
c. Rejected
Tip
โข Creating an already resolved promise: promise.resolve (result)
โข Creating an already rejected promise: promise.reject (error)
13. 13
TYPESCRIPT
Chainability of promise
We can chain promises using the โthenโ function
There are 2 types of declaration spaces in typescript
Type declaration Variable declaration
Best practices
โข Functions variables should be camel case
โข Use pascal case for classes, interface
โข Interface members should be camel case
โข Do not use the prefix I (unconventional lib.d.ts defines important interfaces without an I)
โข Namespaces should be pascal case, enum
โข Donโt make variable undefined but nullable
โข Use โreturn undefinedโ instead of null if itโs a part of A/I or conventional (Nodys error is null by default)
โข Use undefined for next level truthy or falsy.
โข Use error 1=undefined & not error
โข Space b4 type const foo: string=โhelloโ;
โข Prefer single quotes
โข Prefer backticks if possible
โข Donโt use tabs but 2 spaces
โข Use semicolon
Conclusion
Typescript has introduced a new way of writing javascript applications at large scale. With the power of ES6 and above,
the language looks simple, object-oriented and easy to learn. The new features are more, but this e-book describes
some of the important syntax Typescript offered to solve real-world problems JS was facing for years. TypeScript would
be worth a try for large-scale applications.
14. 14
TYPESCRIPT
About Author
Krishnanand Sivaraj is an inquisitive Software Techie and a continuous learner who loves archi-
tecture, debugging and knowledge sharing. Working as a โLead Engineerโ at Softcrylic, he actively
blogs, attends tech-meetups to keep himself updated with futuristic trends.
ยฉ 2018 Softcrylic. All rights reserved. Softcrylic is a registered trademark of Softcrylic, LLC. The above content is proprietary to SoftcrylicApplications
of five common practices
About Softcrylic
Softcrylic helps organizations navigate and execute the path of Digital Transformation through IT solutions and services in
a variety of technical disciplines including Software Development, Test Engineering, Data and Analytics. Since 2000, Soft-
crylic has worked with both start-ups and Fortune 500 organizations to help make their company goals a reality.
Get in Touch with us
Email: info@softcylic.com
Phone: +1 609 452 7638
For more information, visit https://softcrylic.com