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

PPTX
GIT presentation
PPTX
Introduction to React JS for beginners | Namespace IT
PPTX
The Elastic ELK Stack
ODP
OpenShift Enterprise
PDF
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
PPTX
Elastic stack Presentation
PPTX
GitHub Basics - Derek Bable
PPTX
Spring boot
GIT presentation
Introduction to React JS for beginners | Namespace IT
The Elastic ELK Stack
OpenShift Enterprise
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Elastic stack Presentation
GitHub Basics - Derek Bable
Spring boot

What's hot (20)

PPT
Maven Introduction
PDF
Spring Boot
PDF
Git real slides
PDF
Networking in Java with NIO and Netty
PDF
Building layers of defense for your application
PDF
Apache Kafka
PDF
Introduction to Apache Flink - Fast and reliable big data processing
PPTX
Hive + Tez: A Performance Deep Dive
PPTX
Next.js - ReactPlayIO.pptx
PPT
PPTX
Nextjs13.pptx
PDF
Tradeoffs in Distributed Systems Design: Is Kafka The Best? (Ben Stopford and...
PDF
Spring Boot and Microservices
PPTX
GitHub Presentation
PDF
Next.js Introduction
PDF
How to Extend Apache Spark with Customized Optimizations
PPTX
Getting up to speed with MirrorMaker 2 | Mickael Maison, IBM and Ryanne Dolan...
PDF
Testing with JUnit 5 and Spring - Spring I/O 2022
PDF
Fundamentals of Apache Kafka
PPTX
Git branching strategies
Maven Introduction
Spring Boot
Git real slides
Networking in Java with NIO and Netty
Building layers of defense for your application
Apache Kafka
Introduction to Apache Flink - Fast and reliable big data processing
Hive + Tez: A Performance Deep Dive
Next.js - ReactPlayIO.pptx
Nextjs13.pptx
Tradeoffs in Distributed Systems Design: Is Kafka The Best? (Ben Stopford and...
Spring Boot and Microservices
GitHub Presentation
Next.js Introduction
How to Extend Apache Spark with Customized Optimizations
Getting up to speed with MirrorMaker 2 | Mickael Maison, IBM and Ryanne Dolan...
Testing with JUnit 5 and Spring - Spring I/O 2022
Fundamentals of Apache Kafka
Git branching strategies
Ad

Viewers also liked (20)

PPTX
002. Introducere in type script
PPTX
Typescript ppt
PDF
TypeScript - An Introduction
PDF
TypeScript Introduction
PPTX
Why TypeScript?
PPT
TypeScript Presentation
PDF
Александр Русаков - TypeScript 2 in action
PDF
TypeScript: coding JavaScript without the pain
PDF
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
PDF
TypeScript: Un lenguaje aburrido para programadores torpes y tristes
PPTX
TypeScript
PDF
Angular 2 - Typescript
PPTX
Typescript Fundamentals
PDF
Power Leveling your TypeScript
PPTX
Typescript tips & tricks
PDF
TypeScript Seminar
PPTX
TypeScript - Silver Bullet for the Full-stack Developers
PPTX
Typescript
PPTX
TypeScript Overview
PPTX
Introducing type script
002. Introducere in type script
Typescript ppt
TypeScript - An Introduction
TypeScript Introduction
Why TypeScript?
TypeScript Presentation
Александр Русаков - TypeScript 2 in action
TypeScript: coding JavaScript without the pain
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
TypeScript: Un lenguaje aburrido para programadores torpes y tristes
TypeScript
Angular 2 - Typescript
Typescript Fundamentals
Power Leveling your TypeScript
Typescript tips & tricks
TypeScript Seminar
TypeScript - Silver Bullet for the Full-stack Developers
Typescript
TypeScript Overview
Introducing type script
Ad

Similar to TypeScript for Java Developers (20)

PPTX
Getting started with typescript
PDF
Angular for Java Enterprise Developers: Oracle Code One 2018
PDF
Djangocon 2014 angular + django
PDF
JavaScript and UI Architecture Best Practices
KEY
JavaScript Growing Up
PPTX
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
PDF
Building End to-End Web Apps Using TypeScript
PDF
Native Java with GraalVM
PDF
Angular 2 for Java Developers
PPTX
Typescript language extension of java script
PDF
Workshop 23: ReactJS, React & Redux testing
KEY
Código Saudável => Programador Feliz - Rs on Rails 2010
PDF
Intro To JavaScript Unit Testing - Ran Mizrahi
PDF
[2015/2016] JavaScript
PDF
服务框架: Thrift & PasteScript
PDF
Douglas Crockford: Serversideness
PPTX
C# 6.0 Preview
PDF
Symfony2 from the Trenches
PPTX
Hadoop cluster performance profiler
PDF
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Getting started with typescript
Angular for Java Enterprise Developers: Oracle Code One 2018
Djangocon 2014 angular + django
JavaScript and UI Architecture Best Practices
JavaScript Growing Up
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Building End to-End Web Apps Using TypeScript
Native Java with GraalVM
Angular 2 for Java Developers
Typescript language extension of java script
Workshop 23: ReactJS, React & Redux testing
Código Saudável => Programador Feliz - Rs on Rails 2010
Intro To JavaScript Unit Testing - Ran Mizrahi
[2015/2016] JavaScript
服务框架: Thrift & PasteScript
Douglas Crockford: Serversideness
C# 6.0 Preview
Symfony2 from the Trenches
Hadoop cluster performance profiler
WebNet Conference 2012 - Designing complex applications using html5 and knock...

More from Yakov Fain (20)

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

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Electronic commerce courselecture one. Pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Cloud computing and distributed systems.
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
cuic standard and advanced reporting.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Encapsulation theory and applications.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
NewMind AI Monthly Chronicles - July 2025
Reach Out and Touch Someone: Haptics and Empathic Computing
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Electronic commerce courselecture one. Pdf
Big Data Technologies - Introduction.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
Encapsulation_ Review paper, used for researhc scholars
Cloud computing and distributed systems.
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
cuic standard and advanced reporting.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
The AUB Centre for AI in Media Proposal.docx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
20250228 LYD VKU AI Blended-Learning.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...

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