typescript for java developers
Post on 21-Jan-2018
1.117 Views
Preview:
TRANSCRIPT
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 functionsFat 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
InheritanceClassical syntax Prototypal
TypeScript Generics
GenericsGenerics allow using parameterized types
Generics
No Errors - TypeScript uses structural typing, while Java uses the nominal one.
Demo1. node dist/generics.ts2. node dist/generics_comparable.ts
TypeScript Interfaces
Interfaces as custom types
No interfaces here
Implementing interfaces
Demo1. 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 typeUse 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-devnpm 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 itnpm i @types/jqueryui --save-dev
• In the Typescript code import this lib’s global objectimport $ 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.jsdeclare 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
top related