Transcript

{“happymonday”: 3}

TypeScript

(ovvero JavaScript “che non si rompe”)

Antonio Pintus & Federico Pinna

1

[email protected] - [email protected]

The path to HAPPINESS

1. Perché un altro xyzScript?

2. Strumenti di lavoro

3. Tipi base, interfacce e classi

2

Happy Monday!

- Antonio Pintus, Technologist al CRS4, CTO di Paraimpu

- Federico Pinna, CTO di Vivocha

3

Un po’ di storia

Historia magistra vitae

4

JavaScript, a troubled history

JavaScript

ES1

AS1

JScript

ES2

ES3

AS2

compromise

ES5

JScript

ES4

ES3.1

ES6

1995 1997 1998 1999 2005 2008 2009 20152012

TypeScript

TypeScript & JS

TypeScript è un superset di JavaScript

da Microsoft, open source

6

Javascript, a bright future

TypeScript

ES2015

ES5

ES2016ES2017

TypeScript & JS

- Con TypeScript, Microsoft aggiunge al linguaggio:

- tipi

- classi

- interfacce

- moduli

- enum

- ed altro…

8

Perché TypeScript?

JavaScript è bellissimo, ma…

- Refactoring === Refucktoring

- Breaking Changes invisibili

- Difficile da documentare

- Difficile usare codice senza documentazione

9

Perché TypeScript?

function getMovies() { return [ { name: "Big Lebowsky", rating: "****" }, { name: "Shallow Graves", rating: "***" } ]; } for (let i of getMovies()) { console.log( i.name.toUpperCase() + ": " + i.rating.length / 5 * 100 + "%" ); }

10

ES6

Perché TypeScript?

function getMovies() { return [ { title: "Big Lebowsky", rating: "****" }, { title: "Shallow Graves", rating: "***" } ]; } for (let i of getMovies()) { console.log( i.name.toUpperCase() + ": " + i.rating.length / 5 * 100 + "%" ); }

11

ES6

Perché TypeScript?

function getMovies() { return [ { title: "Big Lebowsky", rating: 4.8 }, { title: "Shallow Graves", rating: 3.6 } ]; } for (let i of getMovies()) { console.log( i.name.toUpperCase() + ": " + i.rating.length / 5 * 100 + "%" ); }

12

ES6

Perché TypeScript?

function getMovies(begin, end) { return [ { title: "Big Lebowsky", rating: 4.8 }, { title: "Shallow Graves", rating: 3.6 } ].slice(begin, end); } for (let i of getMovies()) { console.log( i.name.toUpperCase() + ": " + i.rating.length / 5 * 100 + "%" ); }

13

ES6

Perché TypeScript?

Typescript è un ottimo “transpiler” ES6 —> ES5

14

TypeScript & JS

- Non aggiunge un nuovo interprete del codice

- Il “transpiler” tsc genera codice JS standard

15

tsc

TypeScript & ECMAScript 6

Il compilatore TypeScript di default produce JS conforme a ES3

È possibile cambiare il JS target:

tsc --target es6

16

Strumenti di lavoro

1. npm

2. tsc

3. vi

17

18

Non vorrete usare ancora vi, vim o altri fantasmi?

Strumenti di lavoro

1. npm

2. tsc

3. vi editor/IDE

19

Visual Studio Code, free, open source (basato su Atom)

20

Tool: giusto due consigli

JetBrains WebStorm

Strumenti di lavoro

Setup:

1. Installare Node.js!

2. npm install -g typescript

3. npm init

4. tsc --init

5. Creare task in Visual Studio Code

21

Strumenti di lavoro

Documentazione:

www.typescriptlang.org

22

TypeScript: un primo esempio

interface User { id?: string; name: string; surname: string; email?: string; } interface Greetable { greeting(): string; } interface Greeter { (target:Greetable): void; } class RealUser implements User, Greetable { id: string; constructor(public name:string, public surname:string, public email?:string) { this.id = this.name + this.surname + Math.random() * this.surname.length; } greeting():string { return `Hi ${this.name}!`; } } let consoleGreeter:Greeter; consoleGreeter = (target:Greetable) => { console.log(target.greeting()); }

23

Warning: this code is USELESS

Tipi di base

24

Boolean, Numbers

let isAmazing: boolean;

let checked: boolean = false;

let sum: number = 25;

let hex: number = 0xfede;

let discount: number = 0.5;

25

Stringhe

26

let name: string;

let city: string = ‘Cagliari’;

let firstRow: string = `Ciao ${name}`;

Array

27

let ids: string[] = [‘a190’,’b266’c190,’z165’,’xj65’] ;

let firstNum: number[] = [1,2,3];

let arr: Array<number>;

Tuple

28

let t: [number, string];

t = [10, ‘Maradona’];

console.log(t[0]);

Enum

29

enum Language {JavaScript, TypeScript, Python};

let lang: Language;

lang = Language.TypeScript;

lang = Language.Cpp; //ERROR

console.log(Language.Python); //2

enum Language {JavaScript=1, TypeScript, Python};

Any

30

let qualsiasi: any = 2016;

qualsiasi = "duemilasedici";

qualsiasi = true;

Void

31

function log(message): void {

console.log(message);

}

Undefined, Null

32

let u: undefined = undefined;

let n: null = null;

contengono solo i valori corrispondenti

Never

33

rappresenta il tipo di quei valori che non accadranno mai

34

Never

???

Never

35

rappresenta il tipo di quei valori che non accadranno mai

function raiseError(message: string): never {

throw new Error(message);

}

function infiniteLoop(): never {

while (true) {};

}

Interfacce

36

Interfacce

- Descrivere oggetti

- Definire contratti e protocolli

- “normare” il duck typing (structural subtyping)

37

Interfacce

Molto flessibili, possono descrivere qualsiasi tipo esistente:

- Proprietà dichiarate

- Proprietà opzionali

- Proprietà aggiuntive e indicizzate

- Metodi

- Ereditarietà

38

Interfacce

interface User { name:string; email?:string; } interface RegisteredUser extends User { id:string; [flag:string]:boolean; }

interface Logger { (…args[]:any) => void; }

39

Classi

40

Classi

Le classi TypeScript aggiungono a ES6 molte funzionalità:

- Supporto di interfacce multiple (implements)

- Access modifiers: public, protected, private

- Proprietà statiche

- Overload di metodi e costruttori

41

Generics

42

Generics

43

I template di C++ sono tornati!!!

Generics

function genericWrapper<T>(data:T):{ data:T } { return { data }; } console.log(genericWrapper(3)); // { data: 3 }

44

Warning: this code is USELESS

Generics

function eventuallyGet():Promise { return Promise.resolve(5); } eventuallyGet().then((data:string) => { console.log(data.toUpperCase()); });

45

Last topic, ma prima…

46

Per non dimenticare…

JSON

47

Typings

48

Typings

Che succede se uso TypeScript con librerie JavaScript?

49

Typings

50

Typings

.d.ts I typings (declaration files) consentono di descrivere tipi, interfacce e classi di librerie esistenti

NPM supporta i typings, ma è necessario usare TypeScript >= 2.x

$ npm install --save-dev @types/some_module

51

Un esempio:

TypeScript & Express

52

TypeScript + Express: la ricetta

1. bootstrap di un’app Express (e.g. usando express-generator)

2. tsc --init

3. npm install --save @types/express [e tutte le lib necessarie]

4. code & compile & run!

53

54

Link utili

- https://www.typescriptlang.org

- http://microsoft.github.io/TypeSearch

- https://code.visualstudio.com

grazie!

www.bentosa.it

55

happy download

leanpub.com/thewebapinntux56

Training Workshop

Growth Networking

www.bentosa.it

57

58

primo corso

Bentosa!

www.bentosa.it/webapi.html


Top Related