SlideShare una empresa de Scribd logo
1 de 57
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...
Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...
Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...
Simplilearn
 

La actualidad más candente (20)

Angular
AngularAngular
Angular
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
Angular 8
Angular 8 Angular 8
Angular 8
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
An Introduction To Jenkins
An Introduction To JenkinsAn Introduction To Jenkins
An Introduction To Jenkins
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentation
 
Express JS
Express JSExpress JS
Express JS
 
Automation with ansible
Automation with ansibleAutomation with ansible
Automation with ansible
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
 
Introducing Swagger
Introducing SwaggerIntroducing Swagger
Introducing Swagger
 
Presentation of framework Angular
Presentation of framework AngularPresentation of framework Angular
Presentation of framework Angular
 
An Overview on Nuxt.js
An Overview on Nuxt.jsAn Overview on Nuxt.js
An Overview on Nuxt.js
 
NestJS
NestJSNestJS
NestJS
 
Nest.js Introduction
Nest.js IntroductionNest.js Introduction
Nest.js Introduction
 
Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...
Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...
Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 

Destacado

TypeScript Presentation
TypeScript PresentationTypeScript Presentation
TypeScript Presentation
Patrick John Pacaña
 

Destacado (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 Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
 
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
 

Similar a TypeScript for Java Developers

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David 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 JSCoverage
mlilley
 
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
Ran Mizrahi
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
Qiangning Hong
 
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
 

Similar a 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)
 

Más de Yakov Fain

Más de 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
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

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