KEMBAR78
Typescript - Object Oriented Approach in JS | PPTX
TypeScript
OO approach in JS
Piotr Miazga
Agenda
• Jak rozpocząłem przygodę z TS
• Wprowadzenie do TS
• Typy proste, Szablony
• Klasy, Interfejsy, Dziedziczenie
• Typings/DefinitelyTyped
• Przykłady użycia
• Za i przeciw
• Inne projekty
• QA
Dwa słowa o mnie
 Ukrywa się jako PolishDeveloper
 Programista od 9 lat
 Przed snem zamiast dobranocki czytam
CleanCode
 Rajdy to moja pasja
 Gdy nikt nie patrzy gram w Minecrafta
artytmetyka JS
console.log(1 + 1); // 2
console.log(1 + '1'); // '11'
console.log('1' + 1); // '11'
console.log('1' + '1'); // '11'
artytmetyka JS
console.log(1 + 1); // 2
console.log(1 + '1'); // '11'
console.log('1' + 1); // '11'
console.log('1' + '1'); // '11'
console.log(1 - 1); // 0
console.log(1 - '1'); // 0
console.log('1' - 1); // 0
console.log('1' - '1'); // 0
artytmetyka JS
console.log(1 + 1); // 2
console.log(1 + '1'); // '11'
console.log('1' + 1); // '11'
console.log('1' + '1'); // '11'
console.log(1 - 1); // 0
console.log(1 - '1'); // 0
console.log('1' - 1); // 0
console.log('1' - '1'); // 0
console.log('2' - '1' + '1') => ??
console.log('2' - ('1' + '1')) => ??
artytmetyka JS
console.log(1 + 1); // 2
console.log(1 + '1'); // '11'
console.log('1' + 1); // '11'
console.log('1' + '1'); // '11'
console.log(1 - 1); // 0
console.log(1 - '1'); // 0
console.log('1' - 1); // 0
console.log('1' - '1'); // 0
console.log('2' - '1' + '1') => 11
console.log('2' - ('1' + '1')) => -9
WTF cdn
console.log([4] * [4]); //16
console.log([4, 4] * [4, 4]); //Nan
console.log([] * []); //0
console.log([] + []); //""
console.log([] * {}); //NaN
console.log([] + {}); //"[object Object]"
console.log(Array(3) == ',,'); //true
var x = [0];
console.log(x == x); //true
console.log(x == !x); //true
Czas na historyjkę
a wszystko zaczęło się od….
Ty, patrz - typowany JS, wow
Kolejny język ?!
 Powolne przejście na Front-end
 Kod JS robi się coraz większy
 Kod JS robi się coraz bardziej
skomplikowany
 OO jest popularne, ES6 też to ma
 Prototypowanie jest jak battle-axe
 Ale przecież jest już ES6
TS - czym jesteś
 Strict superset of Javascript
 Pierwsza wersja 2012
 Jednym z autorów jest Anders Hejlsberg
 Transpilator
 Typy,Szablony,Klasy,Moduły,Interfejsy o/
Instalacja/użycie
npm install -g tsc
tsc file.ts
tsc —watch file.ts
Let’s code!
Ready ??
Typy proste
enum MessageTypes {'New', 'Read', 'Archived'}
let message: string|string[] = 'abc',
count: number = 123,
isAvailable: boolean = false,
recipientIds: Array<number> = [10, 11, 12],
messageIds: number[],
type:MessageTypes = MessageTypes.New,
transition: 'ease'|'ease-in'|'ease-out',
tmp:any;
Funkcje
function triggerError(message:string):void {
alert('Error ' + message);
}
function add(a:number, b:number):number {
return a+b;
}
//Error:(20, 20) TS2345: Argument of type 'string' is not assignable
to parameter of type 'number'.
function double(value:number) {
return value*2;
}
Interfejsy
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
let obj:LabelledValue;
obj = {size: 10, label: "Size 10 Object"};
printLabel(obj);
Parametry opcjonalne
interface MyObject {
name: string;
size?: number;
}
function printMyObject(object:MyObject) {
let msg:string = 'Element ' + object.name;
if (object.hasOwnProperty('size')) {
msg += '(' + object.size + ')';
}
console.log(msg);
}
let sofa = { name: 'sofa' };
printMyObject(sofa);
Klasy
class Greeter {
constructor(private name:string) {}
greet() {
return `Hello ${this.name}`;
}
}
let greeter = new Greeter('world');
greeter.greet();
Klasy cdn…
class Animal {
constructor(protected name: string) {}
}
class Rhino extends Animal {
constructor() {
super("Rhino");
}
}
class Employee {
constructor(private firstName: string) {}
}
let animal:Animal = new Animal("Kiwi");
let rhino = new Rhino();
let employee = new Employee("Bob");
Klasy cdn 2
let animal:Animal = new Animal("Kiwi");
let rhino = new Rhino();
let employee = new Employee("Bob");
animal = rhino;
animal = employee;
//main.ts(40,1): error TS2322: Type 'Employee' is not assignable
to type 'Animal'.
Real code
Ready ??
Boundary interface
export interface IGetMeterpointStructureResponse {
id: number;
identifier: string;
type: string;
supplyStartDate: Date;
meters: Array<IMeter>;
isEconomy7: boolean;
supplyAddress: IAddress;
}
Promises
getMeterPoints(account: Project.IAccount):
ng.IPromise<Project.IGetMeterpointsResponse> {
var deferred = this.$q.defer(),
link = this.config.getAPILink('id',
{id: account.id}
);
this.$http.get(link).success((response) => {
deferred.resolve(JSON.parse(response));
}).error((reason:Error) => {
deferred.reject(reason);
});
return deferred.promise;
}
RootScope
export interface IRootScope extends
ng.IRootScopeService
{
userAccount: UserProfile;
juniferAccount : Project.IAccount;
errorModal: {
visible:boolean;
message:string;
};
throwError(message:string):void;
}
Controller
export class ErrorModalController {
public static $inject:string[] =[‘$rootScope’];
constructor(private $rootScope:IRootScope) {
$rootScope.errorModal = {
visible: false,
message: null
};
$rootScope.throwError = function(msg:string) {
$rootScope.errorModal.visible = true;
$rootScope.errorModal.message = msg;
};
}
}
Typings
# Install Typings CLI utility.
npm install typings --global
# Search for definitions.
typings search angular
# Find an available definition (by name).
typings search --name react
# Install typings
typings install stripe --save
Czemu nie ES6
Wciąż dynamicznie typowany..
Brak supportu dla nowych przeglądarek(Babel ?)
ES5 – Grudzień 2009
ES6 – Czerwiec 2015
ES7 - WIP
TS1.4 – Styczeń 2014
TS1.5 – Lipiec 2015
TS1.6 – Wrzesień 2015
TS1.7 - Grudzień 2015
TS1.8 - Luty 2016
Za i przeciw
 Działa wszędzie
 Statyczne typowanie
 Programowanie defensywne
 Podejście OO
 Łatwiejsze UnitTesty
 Podpowiadanie składni
 Learning curve
 Dodatkowy proces kompilacji
 Wymaga bindigów które nie zawsze są
Podobne projekty
 ATScript
 Flow (Babel Typecheck)
 JSX
 Dart
Linki
http://www.typescriptlang.org/docs/tutorial.html
https://github.com/typings/typings
QA
Czas na pytania
Dziękuję za uwagę
Twitter:polishdeveloper
Skype:polishdeveloper
GitHub:polishdeveloper
Typescript - Object Oriented Approach in JS

Typescript - Object Oriented Approach in JS

  • 1.
  • 2.
    Agenda • Jak rozpocząłemprzygodę z TS • Wprowadzenie do TS • Typy proste, Szablony • Klasy, Interfejsy, Dziedziczenie • Typings/DefinitelyTyped • Przykłady użycia • Za i przeciw • Inne projekty • QA
  • 3.
    Dwa słowa omnie  Ukrywa się jako PolishDeveloper  Programista od 9 lat  Przed snem zamiast dobranocki czytam CleanCode  Rajdy to moja pasja  Gdy nikt nie patrzy gram w Minecrafta
  • 4.
    artytmetyka JS console.log(1 +1); // 2 console.log(1 + '1'); // '11' console.log('1' + 1); // '11' console.log('1' + '1'); // '11'
  • 5.
    artytmetyka JS console.log(1 +1); // 2 console.log(1 + '1'); // '11' console.log('1' + 1); // '11' console.log('1' + '1'); // '11' console.log(1 - 1); // 0 console.log(1 - '1'); // 0 console.log('1' - 1); // 0 console.log('1' - '1'); // 0
  • 6.
    artytmetyka JS console.log(1 +1); // 2 console.log(1 + '1'); // '11' console.log('1' + 1); // '11' console.log('1' + '1'); // '11' console.log(1 - 1); // 0 console.log(1 - '1'); // 0 console.log('1' - 1); // 0 console.log('1' - '1'); // 0 console.log('2' - '1' + '1') => ?? console.log('2' - ('1' + '1')) => ??
  • 7.
    artytmetyka JS console.log(1 +1); // 2 console.log(1 + '1'); // '11' console.log('1' + 1); // '11' console.log('1' + '1'); // '11' console.log(1 - 1); // 0 console.log(1 - '1'); // 0 console.log('1' - 1); // 0 console.log('1' - '1'); // 0 console.log('2' - '1' + '1') => 11 console.log('2' - ('1' + '1')) => -9
  • 8.
    WTF cdn console.log([4] *[4]); //16 console.log([4, 4] * [4, 4]); //Nan console.log([] * []); //0 console.log([] + []); //"" console.log([] * {}); //NaN console.log([] + {}); //"[object Object]" console.log(Array(3) == ',,'); //true var x = [0]; console.log(x == x); //true console.log(x == !x); //true
  • 9.
    Czas na historyjkę awszystko zaczęło się od…. Ty, patrz - typowany JS, wow
  • 10.
    Kolejny język ?! Powolne przejście na Front-end  Kod JS robi się coraz większy  Kod JS robi się coraz bardziej skomplikowany  OO jest popularne, ES6 też to ma  Prototypowanie jest jak battle-axe  Ale przecież jest już ES6
  • 11.
    TS - czymjesteś  Strict superset of Javascript  Pierwsza wersja 2012  Jednym z autorów jest Anders Hejlsberg  Transpilator  Typy,Szablony,Klasy,Moduły,Interfejsy o/
  • 12.
    Instalacja/użycie npm install -gtsc tsc file.ts tsc —watch file.ts
  • 13.
  • 14.
    Typy proste enum MessageTypes{'New', 'Read', 'Archived'} let message: string|string[] = 'abc', count: number = 123, isAvailable: boolean = false, recipientIds: Array<number> = [10, 11, 12], messageIds: number[], type:MessageTypes = MessageTypes.New, transition: 'ease'|'ease-in'|'ease-out', tmp:any;
  • 15.
    Funkcje function triggerError(message:string):void { alert('Error' + message); } function add(a:number, b:number):number { return a+b; } //Error:(20, 20) TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. function double(value:number) { return value*2; }
  • 16.
    Interfejsy interface LabelledValue { label:string; } function printLabel(labelledObj: LabelledValue) { console.log(labelledObj.label); } let obj:LabelledValue; obj = {size: 10, label: "Size 10 Object"}; printLabel(obj);
  • 17.
    Parametry opcjonalne interface MyObject{ name: string; size?: number; } function printMyObject(object:MyObject) { let msg:string = 'Element ' + object.name; if (object.hasOwnProperty('size')) { msg += '(' + object.size + ')'; } console.log(msg); } let sofa = { name: 'sofa' }; printMyObject(sofa);
  • 18.
    Klasy class Greeter { constructor(privatename:string) {} greet() { return `Hello ${this.name}`; } } let greeter = new Greeter('world'); greeter.greet();
  • 19.
    Klasy cdn… class Animal{ constructor(protected name: string) {} } class Rhino extends Animal { constructor() { super("Rhino"); } } class Employee { constructor(private firstName: string) {} } let animal:Animal = new Animal("Kiwi"); let rhino = new Rhino(); let employee = new Employee("Bob");
  • 20.
    Klasy cdn 2 letanimal:Animal = new Animal("Kiwi"); let rhino = new Rhino(); let employee = new Employee("Bob"); animal = rhino; animal = employee; //main.ts(40,1): error TS2322: Type 'Employee' is not assignable to type 'Animal'.
  • 21.
  • 22.
    Boundary interface export interfaceIGetMeterpointStructureResponse { id: number; identifier: string; type: string; supplyStartDate: Date; meters: Array<IMeter>; isEconomy7: boolean; supplyAddress: IAddress; }
  • 23.
    Promises getMeterPoints(account: Project.IAccount): ng.IPromise<Project.IGetMeterpointsResponse> { vardeferred = this.$q.defer(), link = this.config.getAPILink('id', {id: account.id} ); this.$http.get(link).success((response) => { deferred.resolve(JSON.parse(response)); }).error((reason:Error) => { deferred.reject(reason); }); return deferred.promise; }
  • 24.
    RootScope export interface IRootScopeextends ng.IRootScopeService { userAccount: UserProfile; juniferAccount : Project.IAccount; errorModal: { visible:boolean; message:string; }; throwError(message:string):void; }
  • 25.
    Controller export class ErrorModalController{ public static $inject:string[] =[‘$rootScope’]; constructor(private $rootScope:IRootScope) { $rootScope.errorModal = { visible: false, message: null }; $rootScope.throwError = function(msg:string) { $rootScope.errorModal.visible = true; $rootScope.errorModal.message = msg; }; } }
  • 26.
    Typings # Install TypingsCLI utility. npm install typings --global # Search for definitions. typings search angular # Find an available definition (by name). typings search --name react # Install typings typings install stripe --save
  • 27.
    Czemu nie ES6 Wciążdynamicznie typowany.. Brak supportu dla nowych przeglądarek(Babel ?) ES5 – Grudzień 2009 ES6 – Czerwiec 2015 ES7 - WIP TS1.4 – Styczeń 2014 TS1.5 – Lipiec 2015 TS1.6 – Wrzesień 2015 TS1.7 - Grudzień 2015 TS1.8 - Luty 2016
  • 28.
    Za i przeciw Działa wszędzie  Statyczne typowanie  Programowanie defensywne  Podejście OO  Łatwiejsze UnitTesty  Podpowiadanie składni  Learning curve  Dodatkowy proces kompilacji  Wymaga bindigów które nie zawsze są
  • 29.
    Podobne projekty  ATScript Flow (Babel Typecheck)  JSX  Dart
  • 30.
  • 31.
  • 32.

Editor's Notes

  • #11 Pełny cross-platform Duże projekt staja się projektami read only bo każdy boi sie ich dotknać (nie mozna refaktorowac, jedynie grep) Można kontrolować swój komputer, swoje otoczenie, ale nie można kontrolować komputera Twoich klientów/userów
  • #12 lead architect of C# and creator of Delphi and TurboPascal typowanie per obiekt (np ta klasa ma tylko 3 metody, to sa metody ktorych mozesz uzyc, a nie pokazuje wszysktie metody wszedzie dostepne) a co za tym idzie, możesz typować, albo nie, tak jak chcesz pozwala używać funkcjonalności z przyszłości juz teraz kiedy nie jest typowane TS probuje sam odgadnąć typy, samo doanie typu do parametry dla sortByName(a:any[]) powoduje ze on juz rozkmini co i jak lepsza refaktoryzacja, podpowie tylko uzycie danej klasy, a nie wszystkie uzycia w kodzie (poniewaz js jest dynamiczny i ciezko jest odnalezc gdzie faktycznie jest uzywany dany property)