SlideShare a Scribd company logo
TypeScript for Java
Developers
Yakov Fain

yfain
About myself
• Angular practice lead at Farata Systems
• Java Champion
• Co-authored the book

“Angular 2 Development with TypeScript”
Getting started with
TypeScript
What’s TypeScript?
• An open source superset of JavaScript developed by Microsoft
• Compiles code into JavaScript of various ECMAScript flavors
• Well supported by IDEs
• Official site: http://www.typescriptlang.org
Why use TypeScript?
• Optional static typing
• Supports the latest and evolving JavaScript features
• More productive than JavaScript
• Supports classes, interfaces, generics, annotations, 

public/private/protected access and more
Benefits of the static typing
Benefits of the static typing
TypeScript and IDEs
• Visual Studio Code (free)
• IntelliJ IDEA or WebStorm
• Sublime Text with TypeScript plugin
• Eclipse with TypeScript plugin
Installing the TypeScript compiler
1.IInstall Node.js from https://nodejs.org

2.Install TypeScript compiler globally:



npm i typescript -g

let myName:string;
myName = "Yakov Fain";
console.log(`Hello ${myName}`);
tsc --t es5 hello.ts
1. Create a new file hello.ts
2. Compile hello.ts to hello.js (the ES5 flavor)
Compiling a simple script
Compiler’s options in tsconfig.json
{
"compilerOptions": {
"outDir": "./dist",
"baseUrl": "src",
"sourceMap": true,
"moduleResolution": "node",
"noEmitOnError": true,
"target": “es5",
"watch": true
}
}
How to run code samples
• Install Node.js from https://nodejs.org (use the recommended version)
• Clone or download the repository https://github.com/yfain/ts into any directory
• In the command window, change into this directory
• Install the project dependencies (TypeScript compiler) locally:

npm install
• compile all code samples into the dist directory:

npm run tsc
• To run a code sample (e.g. fatArrow.js):

node dist/fatArrow.js
Fat arrow functions

(similar to lambdas in Java)
Fat arrow functions
Fat arrow function:
Anonymous function:
Fat arrow functions make the
meaning of the this pointer
predictable.
Demo



node dist/fatArrow.js
TypeScript Classes
and Inheritance
A class with constructor:take 1
A class with constructor: take 2
Inheritance
Classical syntax Prototypal
TypeScript Generics
Generics
Generics allow using parameterized types
Generics
No Errors - TypeScript uses structural typing, while Java uses the nominal one.
Demo


1. node dist/generics.ts
2. node dist/generics_comparable.ts
TypeScript Interfaces
Interfaces as custom types
No interfaces
here
Implementing interfaces
Demo
1. node dist/interface-as-type.ts
2. node dist/interface-implements

3. node dist/implement-class.ts
Destructuring Objects in TypeScript
Using destructuring to get specific
object properties
Destructuring in practice
@Component({

selector: 'app',

template: `

<input type="text" placeholder="Enter stock (e.g. AAPL)"
(change)="onInputEvent($event)">

<br/>

`

})

class AppComponent {

stock:string;



onInputEvent({target}):void{

this.stock=target.value;

}

}
Angular
The Union Type
The union type
function padLeft(value: string, padding: number | string ) {...}
Using a vertical bar specify the “either/or” type
The Intersection Type
The intersection type
Use an ampersand to combine types
interface IPerson {
firstName: string;
lastName: string;
age: number;
ssn?: string;
}
interface IEmployee{
title: string;
desk: string;
}
type TheWorker = IPerson & IEmployee;
let worker: TheWorker = {firstName:"John", lastName: "Smith", age:29,
title:"Manager", desk:"A1,234"};
Mixins
Using async and await
From callbacks to promises
to async/await
Callbacks
(function getProductDetails() {
setTimeout(function () {
console.log('Getting customers');
setTimeout(function () {
console.log('Getting orders');
setTimeout(function () {
console.log('Getting products');
setTimeout(function () {
console.log('Getting product details')
}, 1000);
}, 1000);
}, 1000);
}, 1000);
})();
function getCustomers(){
let promise = new Promise(
function (resolve, reject){
console.log("Getting customers");
// Emulate an async server call here
setTimeout(function(){
let success = true;
if (success){
resolve( "John Smith"); // got customer
}else{
reject("Can't get customers");
}
},1000);
}
);
return promise;
}
Promises
function getCustomers(){
let promise = new Promise(
function (resolve, reject){
console.log("Getting customers");
// Emulate an async server call here
setTimeout(function(){
let success = true;
if (success){
resolve( "John Smith"); // got customer
}else{
reject("Can't get customers");
}
},1000);
}
);
return promise;
}
function getOrders(customer){
let promise = new Promise(
function (resolve, reject){
// Emulate an async server call here
setTimeout(function(){
let success = true;
if (success){
resolve( `Found the order 123 for ${customer}`); // got order
}else{
reject("Can't get orders");
}
},1000);
}
);
return promise;
}
Promises
function getCustomers(){
let promise = new Promise(
function (resolve, reject){
console.log("Getting customers");
// Emulate an async server call here
setTimeout(function(){
let success = true;
if (success){
resolve( "John Smith"); // got customer
}else{
reject("Can't get customers");
}
},1000);
}
);
return promise;
}
function getOrders(customer){
let promise = new Promise(
function (resolve, reject){
// Emulate an async server call here
setTimeout(function(){
let success = true;
if (success){
resolve( `Found the order 123 for ${customer}`); // got order
}else{
reject("Can't get orders");
}
},1000);
}
);
return promise;
}
getCustomers()
.then(cust => console.log(cust))
.then(cust => getOrders(cust))
.then(order => console.log(order))
.catch(err => console.error(err));
Promises
async/await
• await - wait until the async code completes
• async - declare a function as asynchronous
async function getCustomersOrders(){
try {
const customer = await getCustomers(); // no callbacks; no then
console.log(`Got customer ${customer}`);
const orders = await getOrders(customer);
console.log(orders);
} catch(err){
console.log(err);
}
}
Demo


node dist/async-await.js

TypeScript Decorators

(think Java annotations)
What’s a Decorator?
• Decorator is a function with metadata about a class,
property, method or a parameter
• Decorators start with the @-sign, e.g. @Component
A sample Angular component with
decorators
@Component({
selector: 'order-processor',
template: `
Buying {{quantity}} shares}
`
})
export class OrderComponent {
@Input() quantity: number;
}
Creating your own class
decorators
function Whoami (target){
console.log(`You are: n ${target}`)
}
@Whoami
class Friend {
constructor(private name: string, private age: number){}
}
Using JavaScript libraries in the
TypeScript code
Type definition files
• Type definition files (*.d.ts) contain type declarations for
JavaScript libraries and frameworks
• *.d.ts files are used by IDE for autocomplete
• TypeScript static analyzer uses *.d.ts files to report errors
• npmjs.org has 3K+ *d.ts files
• https://www.npmjs.com/~types
• Install type definitions, e.g.:



npm i @types/lodash --save-dev

npm i @types/jquery --save-dev
export declare class QueryList<T> {
private _dirty;
private _results;
private _emitter;
readonly changes: Observable<any>;
readonly length: number;
readonly first: T;
readonly last: T;
/**
* See[Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
*/
map<U>(fn: (item: T, index: number, array: T[]) => U): U[];
/**
* See
* [Array.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
*/
filter(fn: (item: T, index: number, array: T[]) => boolean): T[];
/**
* See [Array.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
*/
find(fn: (item: T, index: number, array: T[]) => boolean): T | undefined;
/**
* See[Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
*/
reduce<U>(fn: (prevValue: U, curValue: T, curIndex: number, array: T[]) => U, init: U): U;
/**
* See [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
*/
forEach(fn: (item: T, index: number, array: T[]) => void): void;
...
}
A sample type definitions file
JS libraries in TypeScript apps. Approach 1.
• Add the required library scripts and CSS to index.html:





• Use the lib’s global variable in your TypeScript code:
Drawback: No TypeScript compiler’s errors; no autocomplete
• Install the library 

npm i jqueryui --save
• If the type definition file exists, install it

npm i @types/jqueryui --save-dev
• In the Typescript code import this lib’s global object

import $ from ‘jquery’;
• Add the required css to index.html
JS libraries in TypeScript apps. Approach 2.
Benefits: TypeScript compiler’s errors; autocomplete
Create your own d.ts file
JS libraries in TypeScript apps. Approach 3.
Benefits: TypeScript compiler’s errors; autocomplete
function greeting(name) {
console.log("hello " + name);
}
hello.js
declare function greeting(name: string): void;
src/typings.d.ts
<script> src=“hello.js"></script>
index.html
app.component.ts
Demo


1. cd src/hello-world-ts-jquery

2. npm i live-server -g



3. live-server
Thank you!
• Training inquiries: 

training@faratasystems.com
• My blog:

yakovfain.com

More Related Content

What's hot (20)

PPTX
Typescript ppt
akhilsreyas
 
PDF
Best Practices for ETL with Apache NiFi on Kubernetes - Albert Lewandowski, G...
GetInData
 
PDF
Angular & RXJS: examples and use cases
Fabio Biondi
 
PDF
Apache NiFi Record Processing
Bryan Bende
 
PDF
Gitlab ci-cd
Dan MAGIER
 
PDF
Monitoring Kubernetes with Prometheus
Grafana Labs
 
PDF
Data platform data pipeline(Airflow, Kubernetes)
창언 정
 
PPTX
Learn Apache Spark: A Comprehensive Guide
Whizlabs
 
PPTX
Apache Tez: Accelerating Hadoop Query Processing
Hortonworks
 
PDF
Hadoopの概念と基本的知識
Ken SASAKI
 
PPTX
Introduction to Gitlab | Gitlab 101 | Training Session
Anwarul Islam
 
PDF
Using GitLab CI
ColCh
 
PDF
Spring boot introduction
Rasheed Waraich
 
PDF
Apache Kafka
Diego Pacheco
 
PDF
Git Branching Model
Lemi Orhan Ergin
 
PDF
Introduction to Git and GitHub
Vikram SV
 
PDF
Ansible
Vishal Yadav
 
PDF
HDFS on Kubernetes—Lessons Learned with Kimoon Kim
Databricks
 
PDF
[2D1]Elasticsearch 성능 최적화
NAVER D2
 
PDF
DevOps Powerpoint Presentation Slides
SlideTeam
 
Typescript ppt
akhilsreyas
 
Best Practices for ETL with Apache NiFi on Kubernetes - Albert Lewandowski, G...
GetInData
 
Angular & RXJS: examples and use cases
Fabio Biondi
 
Apache NiFi Record Processing
Bryan Bende
 
Gitlab ci-cd
Dan MAGIER
 
Monitoring Kubernetes with Prometheus
Grafana Labs
 
Data platform data pipeline(Airflow, Kubernetes)
창언 정
 
Learn Apache Spark: A Comprehensive Guide
Whizlabs
 
Apache Tez: Accelerating Hadoop Query Processing
Hortonworks
 
Hadoopの概念と基本的知識
Ken SASAKI
 
Introduction to Gitlab | Gitlab 101 | Training Session
Anwarul Islam
 
Using GitLab CI
ColCh
 
Spring boot introduction
Rasheed Waraich
 
Apache Kafka
Diego Pacheco
 
Git Branching Model
Lemi Orhan Ergin
 
Introduction to Git and GitHub
Vikram SV
 
Ansible
Vishal Yadav
 
HDFS on Kubernetes—Lessons Learned with Kimoon Kim
Databricks
 
[2D1]Elasticsearch 성능 최적화
NAVER D2
 
DevOps Powerpoint Presentation Slides
SlideTeam
 

Viewers also liked (20)

PPTX
002. Introducere in type script
Dmitrii Stoian
 
PDF
TypeScript - An Introduction
NexThoughts Technologies
 
PDF
TypeScript Introduction
Dmitry Sheiko
 
PPTX
Why TypeScript?
FITC
 
PPT
TypeScript Presentation
Patrick John Pacaña
 
PDF
Александр Русаков - TypeScript 2 in action
MoscowJS
 
PDF
TypeScript: coding JavaScript without the pain
Sander Mak (@Sander_Mak)
 
PDF
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
Ontico
 
PDF
TypeScript: Un lenguaje aburrido para programadores torpes y tristes
Micael Gallego
 
PPTX
TypeScript
GetDev.NET
 
PDF
Angular 2 - Typescript
Nathan Krasney
 
PPTX
Typescript Fundamentals
Sunny Sharma
 
PDF
Power Leveling your TypeScript
Offirmo
 
PPTX
Typescript tips & tricks
Ori Calvo
 
PDF
TypeScript Seminar
Haim Michael
 
PPTX
TypeScript - Silver Bullet for the Full-stack Developers
Rutenis Turcinas
 
PPTX
Typescript
Nikhil Thomas
 
PPTX
TypeScript Overview
Aniruddha Chakrabarti
 
PPTX
Introducing type script
Remo Jansen
 
PDF
TypeScript: Angular's Secret Weapon
Laurent Duveau
 
002. Introducere in type script
Dmitrii Stoian
 
TypeScript - An Introduction
NexThoughts Technologies
 
TypeScript Introduction
Dmitry Sheiko
 
Why TypeScript?
FITC
 
TypeScript Presentation
Patrick John Pacaña
 
Александр Русаков - TypeScript 2 in action
MoscowJS
 
TypeScript: coding JavaScript without the pain
Sander Mak (@Sander_Mak)
 
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
Ontico
 
TypeScript: Un lenguaje aburrido para programadores torpes y tristes
Micael Gallego
 
TypeScript
GetDev.NET
 
Angular 2 - Typescript
Nathan Krasney
 
Typescript Fundamentals
Sunny Sharma
 
Power Leveling your TypeScript
Offirmo
 
Typescript tips & tricks
Ori Calvo
 
TypeScript Seminar
Haim Michael
 
TypeScript - Silver Bullet for the Full-stack Developers
Rutenis Turcinas
 
Typescript
Nikhil Thomas
 
TypeScript Overview
Aniruddha Chakrabarti
 
Introducing type script
Remo Jansen
 
TypeScript: Angular's Secret Weapon
Laurent Duveau
 
Ad

Similar to TypeScript for Java Developers (20)

PPTX
Getting started with typescript
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
PDF
Angular for Java Enterprise Developers: Oracle Code One 2018
Loiane Groner
 
PDF
Djangocon 2014 angular + django
Nina Zakharenko
 
PDF
JavaScript and UI Architecture Best Practices
Siarhei Barysiuk
 
KEY
JavaScript Growing Up
David Padbury
 
PPTX
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
mlilley
 
PDF
Building End to-End Web Apps Using TypeScript
Gil Fink
 
PDF
Native Java with GraalVM
Sylvain Wallez
 
PDF
Angular 2 for Java Developers
Yakov Fain
 
PPTX
Typescript language extension of java script
michaelaaron25322
 
PDF
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
KEY
Código Saudável => Programador Feliz - Rs on Rails 2010
Plataformatec
 
PDF
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
PDF
[2015/2016] JavaScript
Ivano Malavolta
 
PDF
服务框架: Thrift & PasteScript
Qiangning Hong
 
PDF
Douglas Crockford: Serversideness
WebExpo
 
PPTX
C# 6.0 Preview
Fujio Kojima
 
PDF
Symfony2 from the Trenches
Jonathan Wage
 
PPTX
Hadoop cluster performance profiler
Ihor Bobak
 
PDF
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
Getting started with typescript
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Loiane Groner
 
Djangocon 2014 angular + django
Nina Zakharenko
 
JavaScript and UI Architecture Best Practices
Siarhei Barysiuk
 
JavaScript Growing Up
David Padbury
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
mlilley
 
Building End to-End Web Apps Using TypeScript
Gil Fink
 
Native Java with GraalVM
Sylvain Wallez
 
Angular 2 for Java Developers
Yakov Fain
 
Typescript language extension of java script
michaelaaron25322
 
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Código Saudável => Programador Feliz - Rs on Rails 2010
Plataformatec
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
[2015/2016] JavaScript
Ivano Malavolta
 
服务框架: Thrift & PasteScript
Qiangning Hong
 
Douglas Crockford: Serversideness
WebExpo
 
C# 6.0 Preview
Fujio Kojima
 
Symfony2 from the Trenches
Jonathan Wage
 
Hadoop cluster performance profiler
Ihor Bobak
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
Ad

More from Yakov Fain (20)

PDF
Type script for_java_dev_jul_2020
Yakov Fain
 
PDF
Web sockets in Angular
Yakov Fain
 
PDF
Using JHipster for generating Angular/Spring Boot apps
Yakov Fain
 
PDF
Using JHipster for generating Angular/Spring Boot apps
Yakov Fain
 
PDF
Reactive Streams and RxJava2
Yakov Fain
 
PDF
Using JHipster 4 for generating Angular/Spring Boot apps
Yakov Fain
 
PDF
Angular 4 for Java Developers
Yakov Fain
 
PDF
Reactive programming in Angular 2
Yakov Fain
 
PDF
Reactive Thinking in Java with RxJava2
Yakov Fain
 
PDF
Angular2 Development for Java developers
Yakov Fain
 
PDF
Reactive Thinking in Java
Yakov Fain
 
PDF
Overview of the AngularJS framework
Yakov Fain
 
PDF
Dart for Java Developers
Yakov Fain
 
PDF
RESTful services and OAUTH protocol in IoT
Yakov Fain
 
PDF
Integrating consumers IoT devices into Business Workflow
Yakov Fain
 
PDF
Intro to JavaScript
Yakov Fain
 
PDF
Seven Versions of One Web Application
Yakov Fain
 
PDF
Java Intro: Unit1. Hello World
Yakov Fain
 
PDF
Running a Virtual Company
Yakov Fain
 
PDF
Princeton jug git_github
Yakov Fain
 
Type script for_java_dev_jul_2020
Yakov Fain
 
Web sockets in Angular
Yakov Fain
 
Using JHipster for generating Angular/Spring Boot apps
Yakov Fain
 
Using JHipster for generating Angular/Spring Boot apps
Yakov Fain
 
Reactive Streams and RxJava2
Yakov Fain
 
Using JHipster 4 for generating Angular/Spring Boot apps
Yakov Fain
 
Angular 4 for Java Developers
Yakov Fain
 
Reactive programming in Angular 2
Yakov Fain
 
Reactive Thinking in Java with RxJava2
Yakov Fain
 
Angular2 Development for Java developers
Yakov Fain
 
Reactive Thinking in Java
Yakov Fain
 
Overview of the AngularJS framework
Yakov Fain
 
Dart for Java Developers
Yakov Fain
 
RESTful services and OAUTH protocol in IoT
Yakov Fain
 
Integrating consumers IoT devices into Business Workflow
Yakov Fain
 
Intro to JavaScript
Yakov Fain
 
Seven Versions of One Web Application
Yakov Fain
 
Java Intro: Unit1. Hello World
Yakov Fain
 
Running a Virtual Company
Yakov Fain
 
Princeton jug git_github
Yakov Fain
 

Recently uploaded (20)

PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 

TypeScript for Java Developers

  • 2. About myself • Angular practice lead at Farata Systems • Java Champion • Co-authored the book
 “Angular 2 Development with TypeScript”
  • 4. What’s TypeScript? • An open source superset of JavaScript developed by Microsoft • Compiles code into JavaScript of various ECMAScript flavors • Well supported by IDEs • Official site: http://www.typescriptlang.org
  • 5. Why use TypeScript? • Optional static typing • Supports the latest and evolving JavaScript features • More productive than JavaScript • Supports classes, interfaces, generics, annotations, 
 public/private/protected access and more
  • 6. Benefits of the static typing
  • 7. Benefits of the static typing
  • 8. TypeScript and IDEs • Visual Studio Code (free) • IntelliJ IDEA or WebStorm • Sublime Text with TypeScript plugin • Eclipse with TypeScript plugin
  • 9. Installing the TypeScript compiler 1.IInstall Node.js from https://nodejs.org
 2.Install TypeScript compiler globally:
 
 npm i typescript -g

  • 10. let myName:string; myName = "Yakov Fain"; console.log(`Hello ${myName}`); tsc --t es5 hello.ts 1. Create a new file hello.ts 2. Compile hello.ts to hello.js (the ES5 flavor) Compiling a simple script
  • 11. Compiler’s options in tsconfig.json { "compilerOptions": { "outDir": "./dist", "baseUrl": "src", "sourceMap": true, "moduleResolution": "node", "noEmitOnError": true, "target": “es5", "watch": true } }
  • 12. How to run code samples • Install Node.js from https://nodejs.org (use the recommended version) • Clone or download the repository https://github.com/yfain/ts into any directory • In the command window, change into this directory • Install the project dependencies (TypeScript compiler) locally:
 npm install • compile all code samples into the dist directory:
 npm run tsc • To run a code sample (e.g. fatArrow.js):
 node dist/fatArrow.js
  • 13. Fat arrow functions
 (similar to lambdas in Java)
  • 14. Fat arrow functions Fat arrow function: Anonymous function:
  • 15. Fat arrow functions make the meaning of the this pointer predictable.
  • 18. A class with constructor:take 1
  • 19. A class with constructor: take 2
  • 22. Generics Generics allow using parameterized types
  • 23. Generics No Errors - TypeScript uses structural typing, while Java uses the nominal one.
  • 24. Demo 
 1. node dist/generics.ts 2. node dist/generics_comparable.ts
  • 26. Interfaces as custom types No interfaces here
  • 28. Demo 1. node dist/interface-as-type.ts 2. node dist/interface-implements
 3. node dist/implement-class.ts
  • 30. Using destructuring to get specific object properties
  • 31. Destructuring in practice @Component({
 selector: 'app',
 template: `
 <input type="text" placeholder="Enter stock (e.g. AAPL)" (change)="onInputEvent($event)">
 <br/>
 `
 })
 class AppComponent {
 stock:string;
 
 onInputEvent({target}):void{
 this.stock=target.value;
 }
 } Angular
  • 33. The union type function padLeft(value: string, padding: number | string ) {...} Using a vertical bar specify the “either/or” type
  • 35. The intersection type Use an ampersand to combine types interface IPerson { firstName: string; lastName: string; age: number; ssn?: string; } interface IEmployee{ title: string; desk: string; } type TheWorker = IPerson & IEmployee; let worker: TheWorker = {firstName:"John", lastName: "Smith", age:29, title:"Manager", desk:"A1,234"};
  • 38. From callbacks to promises to async/await
  • 39. Callbacks (function getProductDetails() { setTimeout(function () { console.log('Getting customers'); setTimeout(function () { console.log('Getting orders'); setTimeout(function () { console.log('Getting products'); setTimeout(function () { console.log('Getting product details') }, 1000); }, 1000); }, 1000); }, 1000); })();
  • 40. function getCustomers(){ let promise = new Promise( function (resolve, reject){ console.log("Getting customers"); // Emulate an async server call here setTimeout(function(){ let success = true; if (success){ resolve( "John Smith"); // got customer }else{ reject("Can't get customers"); } },1000); } ); return promise; } Promises
  • 41. function getCustomers(){ let promise = new Promise( function (resolve, reject){ console.log("Getting customers"); // Emulate an async server call here setTimeout(function(){ let success = true; if (success){ resolve( "John Smith"); // got customer }else{ reject("Can't get customers"); } },1000); } ); return promise; } function getOrders(customer){ let promise = new Promise( function (resolve, reject){ // Emulate an async server call here setTimeout(function(){ let success = true; if (success){ resolve( `Found the order 123 for ${customer}`); // got order }else{ reject("Can't get orders"); } },1000); } ); return promise; } Promises
  • 42. function getCustomers(){ let promise = new Promise( function (resolve, reject){ console.log("Getting customers"); // Emulate an async server call here setTimeout(function(){ let success = true; if (success){ resolve( "John Smith"); // got customer }else{ reject("Can't get customers"); } },1000); } ); return promise; } function getOrders(customer){ let promise = new Promise( function (resolve, reject){ // Emulate an async server call here setTimeout(function(){ let success = true; if (success){ resolve( `Found the order 123 for ${customer}`); // got order }else{ reject("Can't get orders"); } },1000); } ); return promise; } getCustomers() .then(cust => console.log(cust)) .then(cust => getOrders(cust)) .then(order => console.log(order)) .catch(err => console.error(err)); Promises
  • 43. async/await • await - wait until the async code completes • async - declare a function as asynchronous async function getCustomersOrders(){ try { const customer = await getCustomers(); // no callbacks; no then console.log(`Got customer ${customer}`); const orders = await getOrders(customer); console.log(orders); } catch(err){ console.log(err); } }
  • 46. What’s a Decorator? • Decorator is a function with metadata about a class, property, method or a parameter • Decorators start with the @-sign, e.g. @Component
  • 47. A sample Angular component with decorators @Component({ selector: 'order-processor', template: ` Buying {{quantity}} shares} ` }) export class OrderComponent { @Input() quantity: number; }
  • 48. Creating your own class decorators function Whoami (target){ console.log(`You are: n ${target}`) } @Whoami class Friend { constructor(private name: string, private age: number){} }
  • 49. Using JavaScript libraries in the TypeScript code
  • 50. Type definition files • Type definition files (*.d.ts) contain type declarations for JavaScript libraries and frameworks • *.d.ts files are used by IDE for autocomplete • TypeScript static analyzer uses *.d.ts files to report errors
  • 51. • npmjs.org has 3K+ *d.ts files • https://www.npmjs.com/~types • Install type definitions, e.g.:
 
 npm i @types/lodash --save-dev
 npm i @types/jquery --save-dev
  • 52. export declare class QueryList<T> { private _dirty; private _results; private _emitter; readonly changes: Observable<any>; readonly length: number; readonly first: T; readonly last: T; /** * See[Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) */ map<U>(fn: (item: T, index: number, array: T[]) => U): U[]; /** * See * [Array.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) */ filter(fn: (item: T, index: number, array: T[]) => boolean): T[]; /** * See [Array.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) */ find(fn: (item: T, index: number, array: T[]) => boolean): T | undefined; /** * See[Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) */ reduce<U>(fn: (prevValue: U, curValue: T, curIndex: number, array: T[]) => U, init: U): U; /** * See [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) */ forEach(fn: (item: T, index: number, array: T[]) => void): void; ... } A sample type definitions file
  • 53. JS libraries in TypeScript apps. Approach 1. • Add the required library scripts and CSS to index.html:
 
 
 • Use the lib’s global variable in your TypeScript code: Drawback: No TypeScript compiler’s errors; no autocomplete
  • 54. • Install the library 
 npm i jqueryui --save • If the type definition file exists, install it
 npm i @types/jqueryui --save-dev • In the Typescript code import this lib’s global object
 import $ from ‘jquery’; • Add the required css to index.html JS libraries in TypeScript apps. Approach 2. Benefits: TypeScript compiler’s errors; autocomplete
  • 55. Create your own d.ts file JS libraries in TypeScript apps. Approach 3. Benefits: TypeScript compiler’s errors; autocomplete function greeting(name) { console.log("hello " + name); } hello.js declare function greeting(name: string): void; src/typings.d.ts <script> src=“hello.js"></script> index.html app.component.ts
  • 56. Demo 
 1. cd src/hello-world-ts-jquery
 2. npm i live-server -g
 
 3. live-server
  • 57. Thank you! • Training inquiries: 
 [email protected] • My blog:
 yakovfain.com