SlideShare ist ein Scribd-Unternehmen logo
1 von 57
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painSander Mak (@Sander_Mak)
 
Jenkins for java world
Jenkins for java worldJenkins for java world
Jenkins for java worldAshok Kumar
 
Atomicity In Redis: Thomas Hunter
Atomicity In Redis: Thomas HunterAtomicity In Redis: Thomas Hunter
Atomicity In Redis: Thomas HunterRedis Labs
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquareApigee | Google Cloud
 
Developing Terraform Modules at Scale - HashiTalks 2021
Developing Terraform Modules at Scale - HashiTalks 2021Developing Terraform Modules at Scale - HashiTalks 2021
Developing Terraform Modules at Scale - HashiTalks 2021TomStraub5
 
OpenAPI Intro (1).pdf
OpenAPI Intro (1).pdfOpenAPI Intro (1).pdf
OpenAPI Intro (1).pdfPostman
 
[2019] 바르게, 빠르게! Reactive를 품은 Spring Kafka
[2019] 바르게, 빠르게! Reactive를 품은 Spring Kafka[2019] 바르게, 빠르게! Reactive를 품은 Spring Kafka
[2019] 바르게, 빠르게! Reactive를 품은 Spring KafkaNHN FORWARD
 
MeetUp Monitoring with Prometheus and Grafana (September 2018)
MeetUp Monitoring with Prometheus and Grafana (September 2018)MeetUp Monitoring with Prometheus and Grafana (September 2018)
MeetUp Monitoring with Prometheus and Grafana (September 2018)Lucas Jellema
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudEberhard Wolff
 
Docker introduction
Docker introductionDocker introduction
Docker introductionPhuc Nguyen
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
A year with event sourcing and CQRS
A year with event sourcing and CQRSA year with event sourcing and CQRS
A year with event sourcing and CQRSSteve Pember
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js ExpressEyal Vardi
 

Was ist angesagt? (20)

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
 
Jenkins for java world
Jenkins for java worldJenkins for java world
Jenkins for java world
 
Atomicity In Redis: Thomas Hunter
Atomicity In Redis: Thomas HunterAtomicity In Redis: Thomas Hunter
Atomicity In Redis: Thomas Hunter
 
Api presentation
Api presentationApi presentation
Api presentation
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at Square
 
API
APIAPI
API
 
Developing Terraform Modules at Scale - HashiTalks 2021
Developing Terraform Modules at Scale - HashiTalks 2021Developing Terraform Modules at Scale - HashiTalks 2021
Developing Terraform Modules at Scale - HashiTalks 2021
 
TypeScript intro
TypeScript introTypeScript intro
TypeScript intro
 
OpenAPI Intro (1).pdf
OpenAPI Intro (1).pdfOpenAPI Intro (1).pdf
OpenAPI Intro (1).pdf
 
[2019] 바르게, 빠르게! Reactive를 품은 Spring Kafka
[2019] 바르게, 빠르게! Reactive를 품은 Spring Kafka[2019] 바르게, 빠르게! Reactive를 품은 Spring Kafka
[2019] 바르게, 빠르게! Reactive를 품은 Spring Kafka
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
MeetUp Monitoring with Prometheus and Grafana (September 2018)
MeetUp Monitoring with Prometheus and Grafana (September 2018)MeetUp Monitoring with Prometheus and Grafana (September 2018)
MeetUp Monitoring with Prometheus and Grafana (September 2018)
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring Cloud
 
Advanced Terraform
Advanced TerraformAdvanced Terraform
Advanced Terraform
 
Docker introduction
Docker introductionDocker introduction
Docker introduction
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 
A year with event sourcing and CQRS
A year with event sourcing and CQRSA year with event sourcing and CQRS
A year with event sourcing and CQRS
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 

Andere mochten auch

002. Introducere in type script
002. Introducere in type script002. Introducere in type script
002. Introducere in type scriptDmitrii Stoian
 
Александр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in actionАлександр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in actionMoscowJS
 
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)Ontico
 
TypeScript: Un lenguaje aburrido para programadores torpes y tristes
TypeScript: Un lenguaje aburrido para programadores torpes y tristesTypeScript: Un lenguaje aburrido para programadores torpes y tristes
TypeScript: Un lenguaje aburrido para programadores torpes y tristesMicael Gallego
 
Angular 2 - Typescript
Angular 2  - TypescriptAngular 2  - Typescript
Angular 2 - TypescriptNathan Krasney
 
Typescript Fundamentals
Typescript FundamentalsTypescript Fundamentals
Typescript FundamentalsSunny Sharma
 
Power Leveling your TypeScript
Power Leveling your TypeScriptPower Leveling your TypeScript
Power Leveling your TypeScriptOffirmo
 
Typescript tips & tricks
Typescript tips & tricksTypescript tips & tricks
Typescript tips & tricksOri Calvo
 
TypeScript Seminar
TypeScript SeminarTypeScript Seminar
TypeScript SeminarHaim Michael
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersRutenis Turcinas
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type scriptRemo Jansen
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponLaurent Duveau
 
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21MoscowJS
 

Andere mochten auch (20)

002. Introducere in type script
002. Introducere in type script002. Introducere in type script
002. Introducere in type script
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
 
TypeScript Presentation
TypeScript PresentationTypeScript Presentation
TypeScript Presentation
 
Александр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in actionАлександр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in action
 
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
 
TypeScript: Un lenguaje aburrido para programadores torpes y tristes
TypeScript: Un lenguaje aburrido para programadores torpes y tristesTypeScript: Un lenguaje aburrido para programadores torpes y tristes
TypeScript: Un lenguaje aburrido para programadores torpes y tristes
 
TypeScript
TypeScriptTypeScript
TypeScript
 
Angular 2 - Typescript
Angular 2  - TypescriptAngular 2  - Typescript
Angular 2 - Typescript
 
Typescript Fundamentals
Typescript FundamentalsTypescript Fundamentals
Typescript Fundamentals
 
Power Leveling your TypeScript
Power Leveling your TypeScriptPower Leveling your TypeScript
Power Leveling your TypeScript
 
Typescript tips & tricks
Typescript tips & tricksTypescript tips & tricks
Typescript tips & tricks
 
TypeScript Seminar
TypeScript SeminarTypeScript Seminar
TypeScript Seminar
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack Developers
 
Typescript
TypescriptTypescript
Typescript
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type script
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
 
TypeScript
TypeScriptTypeScript
TypeScript
 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
 
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
 

Ähnlich wie TypeScript for Java Developers

Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Loiane Groner
 
Djangocon 2014 angular + django
Djangocon 2014 angular + djangoDjangocon 2014 angular + django
Djangocon 2014 angular + djangoNina Zakharenko
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesSiarhei Barysiuk
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoveragemlilley
 
Building End to-End Web Apps Using TypeScript
Building End to-End Web Apps Using TypeScriptBuilding End to-End Web Apps Using TypeScript
Building End to-End Web Apps Using TypeScriptGil Fink
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVMSylvain Wallez
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java DevelopersYakov Fain
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java scriptmichaelaaron25322
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Plataformatec
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScriptQiangning Hong
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the TrenchesJonathan Wage
 
Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profilerIhor Bobak
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)James Titcumb
 

Ähnlich wie TypeScript for Java Developers (20)

Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
Djangocon 2014 angular + django
Djangocon 2014 angular + djangoDjangocon 2014 angular + django
Djangocon 2014 angular + django
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
 
Building End to-End Web Apps Using TypeScript
Building End to-End Web Apps Using TypeScriptBuilding End to-End Web Apps Using TypeScript
Building End to-End Web Apps Using TypeScript
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVM
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java Developers
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
C# 6.0 Preview
C# 6.0 PreviewC# 6.0 Preview
C# 6.0 Preview
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profiler
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
 

Mehr von Yakov Fain

Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Yakov Fain
 
Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in AngularYakov Fain
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsYakov Fain
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsYakov Fain
 
Reactive Streams and RxJava2
Reactive Streams and RxJava2Reactive Streams and RxJava2
Reactive Streams and RxJava2Yakov Fain
 
Using JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot appsUsing JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot appsYakov Fain
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java DevelopersYakov Fain
 
Reactive programming in Angular 2
Reactive programming in Angular 2Reactive programming in Angular 2
Reactive programming in Angular 2Yakov Fain
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Yakov Fain
 
Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developersYakov Fain
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in JavaYakov Fain
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework Yakov Fain
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java DevelopersYakov Fain
 
RESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTRESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTYakov Fain
 
Integrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowIntegrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowYakov Fain
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScriptYakov Fain
 
Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web ApplicationYakov Fain
 
Java Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldJava Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldYakov Fain
 
Running a Virtual Company
Running a Virtual CompanyRunning a Virtual Company
Running a Virtual CompanyYakov Fain
 
Princeton jug git_github
Princeton jug git_githubPrinceton jug git_github
Princeton jug git_githubYakov Fain
 

Mehr von Yakov Fain (20)

Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020
 
Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in Angular
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot apps
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot apps
 
Reactive Streams and RxJava2
Reactive Streams and RxJava2Reactive Streams and RxJava2
Reactive Streams and RxJava2
 
Using JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot appsUsing JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot apps
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
 
Reactive programming in Angular 2
Reactive programming in Angular 2Reactive programming in Angular 2
Reactive programming in Angular 2
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2
 
Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developers
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in Java
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
RESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTRESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoT
 
Integrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowIntegrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business Workflow
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web Application
 
Java Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldJava Intro: Unit1. Hello World
Java Intro: Unit1. Hello World
 
Running a Virtual Company
Running a Virtual CompanyRunning a Virtual Company
Running a Virtual Company
 
Princeton jug git_github
Princeton jug git_githubPrinceton jug git_github
Princeton jug git_github
 

Kürzlich hochgeladen

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 

Kürzlich hochgeladen (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

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: 
 training@faratasystems.com • My blog:
 yakovfain.com