TypeScript, ovvero JavaScript che "non si rompe"
-
Upload
bentosa -
Category
Technology
-
view
216 -
download
0
Transcript of TypeScript, ovvero JavaScript che "non si rompe"
{“happymonday”: 3}
TypeScript
(ovvero JavaScript “che non si rompe”)
Antonio Pintus & Federico Pinna
1
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
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
- 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
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
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
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
Boolean, Numbers
let isAmazing: boolean;
let checked: boolean = false;
let sum: number = 25;
let hex: number = 0xfede;
let discount: number = 0.5;
25
Array
27
let ids: string[] = [‘a190’,’b266’c190,’z165’,’xj65’] ;
let firstNum: number[] = [1,2,3];
let arr: Array<number>;
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};
Undefined, Null
32
let u: undefined = undefined;
let n: null = null;
contengono solo i valori corrispondenti
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
- 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
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
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
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
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