Upload
piotr-miazga
View
183
Download
2
Embed Size (px)
Citation preview
TypeScriptOO 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• Q\A
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 JSconsole.log(1 + 1); // 2console.log(1 + '1'); // '11'console.log('1' + 1); // '11'console.log('1' + '1'); // '11'
artytmetyka JSconsole.log(1 + 1); // 2console.log(1 + '1'); // '11'console.log('1' + 1); // '11'console.log('1' + '1'); // '11'
console.log(1 - 1); // 0console.log(1 - '1'); // 0console.log('1' - 1); // 0console.log('1' - '1'); // 0
artytmetyka JSconsole.log(1 + 1); // 2console.log(1 + '1'); // '11'console.log('1' + 1); // '11'console.log('1' + '1'); // '11'
console.log(1 - 1); // 0console.log(1 - '1'); // 0console.log('1' - 1); // 0console.log('1' - '1'); // 0
console.log('2' - '1' + '1') => ??console.log('2' - ('1' + '1')) => ??
artytmetyka JSconsole.log(1 + 1); // 2console.log(1 + '1'); // '11'console.log('1' + 1); // '11'console.log('1' + '1'); // '11'
console.log(1 - 1); // 0console.log(1 - '1'); // 0console.log('1' - 1); // 0console.log('1' - '1'); // 0
console.log('2' - '1' + '1') => 11console.log('2' - ('1' + '1')) => -9
WTF cdnconsole.log([4] * [4]); //16console.log([4, 4] * [4, 4]); //Nan
console.log([] * []); //0console.log([] + []); //""
console.log([] * {}); //NaNconsole.log([] + {}); //"[object Object]"
console.log(Array(3) == ',,'); //true
var x = [0];console.log(x == x); //trueconsole.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.tstsc —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;}
Interfejsyinterface LabelledValue { label: string;}
function printLabel(labelledObj: LabelledValue) { console.log(labelledObj.label);}
let obj:LabelledValue;obj = {size: 10, label: "Size 10 Object"};
printLabel(obj);
Parametry opcjonalneinterface 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);
Klasyclass 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 2let 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;}
PromisesgetMeterPoints(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;}
RootScopeexport interface IRootScope extends ng.IRootScopeService{ userAccount: UserProfile; juniferAccount : Project.IAccount; errorModal: { visible:boolean; message:string; }; throwError(message:string):void;}
Controllerexport 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 typingstypings install stripe --save
Czemu nie ES6Wciąż dynamicznie typowany..Brak supportu dla nowych przeglądarek(Babel ?)
ES5 – Grudzień 2009ES6 – Czerwiec 2015ES7 - WIP
TS1.4 – Styczeń 2014TS1.5 – Lipiec 2015TS1.6 – Wrzesień 2015 TS1.7 - Grudzień 2015TS1.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
Q\A
Czas na pytania
Dziękuję za uwagę
Twitter:polishdeveloperSkype:polishdeveloperGitHub:polishdeveloper