typescript presentation - jason haffey

22
TYPESCRIPT THE NEXT FRONTIER

Upload: ralph-johnson

Post on 13-Apr-2017

113 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: TypeScript Presentation - Jason Haffey

TYPESCRIPT

THE NEXT FRONTIER

Page 2: TypeScript Presentation - Jason Haffey

I t ’s JavaScr ipt…

Yep, i ts TypeScriptI t ’s a scr ipt…?

Page 3: TypeScript Presentation - Jason Haffey

What is TypeScript and why should we use it?

• TypeScript is a SUPERSET of JavaScript….But use it respectfully.• Any JavaScript is Valid TypeScript

//JAVASCRIPTvar myString1 = "Hello";var myString2 = "World!";var finalString = myString1 + " " + myString2;

//TYPESCRIPTvar myString1 = "Hello";var myString2 = "World!";var finalString = myString1 + " " + myString2;

Two Exceptions:1. JavaScript’s With Statements2. Vender Specific Extensions – i.e.: Mozilla’s CONST

…..Well sort of

• So what ‘problems’ does TypeScript solve in JavaScript then?• Prototypal Inheritance• Management of Modules (namespaces)• Scoping• Lack of Types

3

Page 4: TypeScript Presentation - Jason Haffey

4

What is TypeScript and why should we use it?

var FelineSoft; (function (FelineSoft) {     var Employee = (function () {         function Employee(options) {             this.firstName = options.firstName;             this.lastName = options.lastName;             this.payType = options.payType;             this.payRate = options.payRate;             this.title = options.title || "";         }         Employee.prototype.calculatePay = function (hoursWorked) {             if (this.payType === PayType.Hourly) {                 var pay = new Pay();                 return pay.calculatePay(hoursWorked, this.payRate);             }             else {                 return this.payRate;             }         };         Employee.prototype.fireThem = function () {   return this.firstName + " " + this.lastName + ", you are FIRED!";  };         return Employee;     })();     FelineSoft.Employee = Employee;     var Pay = (function () {         function Pay() {         }         Pay.prototype.calculatePay = function (hours, poundsPerHour) {  return hours * poundsPerHour; };         return Pay;     })();     var PayType;     (function (PayType) {         PayType[PayType["Hourly"] = 0] = "Hourly";         PayType[PayType["Salary"] = 1] = "Salary";     })(PayType || (PayType = {})); })(FelineSoft || (FelineSoft = {}));

namespace  FelineSoft {     export class Employee {         private firstName: string;         private lastName: string;         private payType: PayType;         private payRate: number;         private title: string;         constructor(options: IEmployeOptions) {             this.firstName = options.firstName;             this.lastName = options.lastName;             this.payType = options.payType;             this.payRate = options.payRate;             this.title = options.title || "";         }         calculatePay(hoursWorked: number): number {             if (this.payType === PayType.Hourly) {                 const pay = new Pay();                 return pay.calculatePay(hoursWorked, this.payRate);             }             else { return this.payRate; }         }         fireThem(): string {  return this.firstName + " " + this.lastName + ", you are FIRED!";  }     }     class Pay {         calculatePay(hours: number, poundsPerHour: number): number { return hours * poundsPerHour;  }     }     enum PayType {         Hourly = 0,         Salary = 1     }     // DOES NOT CONVERT TO JAVASCRIPT     export interface IEmployeOptions {         firstName: string;         lastName: string;         payType: PayType;         payRate: number;         title?: string;     } }

Page 5: TypeScript Presentation - Jason Haffey

5

TypeScript and Visual Studio

• TypeScript – Kind of Important (Current Version 1.8.4)

Page 6: TypeScript Presentation - Jason Haffey

6

TypeScript and Visual Studio

• Web Essentials (Current Version 2015.1)

Page 7: TypeScript Presentation - Jason Haffey

7

TypeScript and Visual Studio

• Basic Visual Studio Settings for TypeScript

Page 8: TypeScript Presentation - Jason Haffey

8

TypeScript and Visual Studio

Page 9: TypeScript Presentation - Jason Haffey

9

TypeScript and Visual Studio

Page 10: TypeScript Presentation - Jason Haffey

10

TypeScript and Visual Studio

Page 11: TypeScript Presentation - Jason Haffey

11

The TypeScript Basics

Variables• The First Character must be:

• Uppercase Letter• Lowercase Letter• Underscore• Dollar Sign <= Warning

• Reserved Words

var ThisIsValid;var thisIsValid;var _andthisIsValid;var $AlsoValid;

break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with implements interface let package private protected public static yield any boolean number string symbol abstract as async await constructor declare from get is module namespace of require set type

Page 12: TypeScript Presentation - Jason Haffey

12

The TypeScript Basics

Types

namespace Presentation {    var badGlobalVariable;    var goodGlobalString: string;

    export class BadClass {        classVariable;    }

    export class GoodClass {        classString: string;    }}

var Presentation;(function (Presentation) {    var badGlobalVariable;    var goodGlobalString;    var BadClass = (function () {        function BadClass() {        }        return BadClass;    })();    Presentation.BadClass = BadClass;    var GoodClass = (function () {        function GoodClass() {        }        return GoodClass;    })();    Presentation.GoodClass = GoodClass;})(Presentation || (Presentation = {}));

• Declaring a type is optional, but then you defeat the point of using TypeScript• To declare a type, use this syntax:

• In a namespace/module• var myString: string;

• In a class• myString: string;

• What types are available in TypeScript?• Strings• Booleans• Numbers (all numbers, integers, decimals, floats, etc.)• Objects• Arrays• Enumerations / Bit Flags• Any

Page 13: TypeScript Presentation - Jason Haffey

13

The TypeScript Basics

Operations

• Increment / Decrement : ++ / --• Math: + - * / %• String to Number Converter: +string or –string• Bit Wise: << >> >>> & ^ | ~• Not Operator: ! !!• And Operator: &&• Or Operator: ||• Type Operator: typeof instanceof in delete

namespace Presentation {    export class Foo {        myString: string = "1";        myNumber: number = 1;

        addStringAndNumber(): number {            return this.myNumber + +this.myString;        }

        subtractStringAndNumber(): number {            return this.myNumber - +this.myString;        }    }}

namespace Presentation {    export class Foo {        truthyString: string = 'Truthy string';        falseyString: string;

        test(): void {            // False, it checks the string but inverts the truth            var invertedTest = !this.truthyString;

            // True, the string is not undefined or empty            var truthyTest = !!this.truthyString;

            // False, the string is empty            var falseyTest = !!this.falseyString;        }    

    }}

Page 14: TypeScript Presentation - Jason Haffey

14

The TypeScript Basics

Functions• Functions are just Methods• Inside a class, just the name• Outside a class, you must include the keyword ‘function’• Parameters

• Optional Parameters• Default Parameters• Rest Parameters

• Overloads• Arrow Functions• Return Values

namespace Presentation {    export class Foo {        myClassMethod(): void {            //DO SOMETHING        }    }

    function myGlobalFunction(): void {        //DO SOMETHING    }}

namespace Presentation {    export class Foo {        getString(): string {            return "Hello World!";        }        getNumber(): number {            return 1;        }        getNothing(): void {            // HA HA HA, nothing to return        }    }}

namespace Presentation {    export class Foo {        getAverage(a: string, b: string, c: string): string;        getAverage(a: number, b: number, c: number): string;        getAverage(a: any, b: any, c: any): string {            var total = parseInt(a, 10) + parseInt(b, 10) + parseInt(c, 10);            var average = total / 3;            return `The average is ${average}`;        }    }}

namespace Presentation {    export class Foo {        methodWithOptionalParams(param?: string): void {            //DO SOMETHING        }

        methodWithDefaultParams(param: string = "default"): void {            //DO SOMETHING        }

        methodWithRestParams(...param: string[]): void {            //DO SOMETHING        }    }}

Page 15: TypeScript Presentation - Jason Haffey

15

The TypeScript Basics

NameSpaces

• Namespaces used to be referred to as Modules• Namespaces can be nested

• Top level namespaces do not need to be mark for export• Anything accessed by something outside of its parent

namespace must be marked for export

namespace Presentation {    export class MyClass {        myString: string;        myNumber: number;

        constructor() {            this.myString = "Hello World!";            this.myNumber = 42;        }    }}

namespace Level1 {    namespace Level2a {        export class L2aClass {

        }

        Level1.Level2b.L2bClass // ACCESSABLE    }

    export namespace Level2b {        export class L2bClass {                    }

        Level1.level2a.L2aClass // NOT ACCESSABLE    }}

namespace LevelA {    Level1.Level2a.L2aClass // NOT ACCESSABLE    Level1.Level2b.L2bClass // ACCESSABLE}

module Presentation {    export class MyClass {        myString: string;        myNumber: number;

        constructor() {            this.myString = "Hello World!";            this.myNumber = 42;        }            }}

Page 16: TypeScript Presentation - Jason Haffey

16

The TypeScript Basics

Interfaces• Interfaces are used solely by TypeScript, no JavaScript is created• Interfaces can be used model an ‘virtual object’• Interfaces can use Inheritance• Interfaces are just Interfaces

• But they support optional fields• Interfaces support Generics

• Type Constraints can be used using EXTENDS

namespace Presentation {    interface ICar {        engine: string;        color: string;    }

    class Car implements ICar {        constructor(engine: string, color: string) {            this.engine = engine;            this.color = color;        }

        engine: string;        color: string;    }}

namespace Presentation {    interface ICar {        engine: string;        color: string;    }

    class Car implements ICar {        constructor(data: ICar) {            this.engine = data.engine;            this.color = data.color;        }

        engine: string;        color: string;    }

    var myCar = new Car({ engine : "FAST", color : "BLACK" });}

Page 17: TypeScript Presentation - Jason Haffey

17

The TypeScript Basics

Interfaces

namespace Presentation {    interface IEngine {        type: string;    }

    interface ICar<T extends IEngine> {        engine: T;        color: string;    }

    class SlowEngine implements IEngine {        type = "slow :(";    }

    class FastEngine implements IEngine {        type = "FAST :)";    }

    class MySlowCar implements ICar<SlowEngine> {        engine: SlowEngine;        color: string;    }

    class MyFastCar implements ICar<FastEngine> {        engine: FastEngine;        color: string;    }}

namespace Presentation {    interface ICar {        engine: string;        color: string;    }

    interface IBasicCar extends ICar {        doors: number;    }

    class Car implements IBasicCar {        constructor(engine: string, color: string, doors: number) {            this.engine = engine;            this.color = color;            this.doors = doors;        }

        engine: string;        color: string;        doors: number;    }}

Page 18: TypeScript Presentation - Jason Haffey

18

The TypeScript Basics

Classes• Constructors use the keyword, constructor, and never have a return type• Classes have Fields, Properties and Methods

• Access Modifiers can be used but ONLY apply within TypeScript• Classes can use Inheritances

• Classes IMPLEMENTS interfaces• Classes EXTENDS other classes

• Classes support Generics• Type Constraints can be used

namespace Presentation {    class MyClass {        constructor() {                    }    }}

namespace Presentation {    class MyClass {        private _value: string;

        constructor() {        }

        myField: string;

        myMethod(): void {            //DO SOME WORK HERE                }

        get value() {            return this._value;        }

        set value(item: string) {            this._value = item;        }    }}

namespace Presentation {    class MyClass {        constructor() {                    }

        private myPrivateProperty: string;        public myPublicProperty: string;        protected myProtectedProperty: string;

        public myPublicMethod(): void {            //DO SOME WORK FOR ANYONE        }

        private myPrivateMethod(): void {            // DO SOME INTERNAL WORK        }

        protected myProtectedMethod(): void {            // DO SOME WORK FOR MY FRIEND        }    }}

Page 19: TypeScript Presentation - Jason Haffey

19

The TypeScript Basics

Classes

namespace Presentation {    class MyClass<T> {        private id: T;        constructor(id: T) {            this.id = id;        }

        myId(): T {            return this.id;        }    }}

namespace Presentation {    class MyClass {        constructor() {                    }

        private myPrivateProperty: string;        public myPublicProperty: string;        protected myProtectedProperty: string;

        public myPublicMethod(): void {            //DO SOME WORK FOR ANYONE        }

        private myPrivateMethod(): void {            // DO SOME INTERNAL WORK        }

        protected myProtectedMethod(): void {            // DO SOME WORK FOR MY FRIEND        }    }

    class ChildClass extends MyClass {        constructor() {            super();            this.myProtectedMethod(); // ACCESSABLE            this.myProtectedProperty = ""; // ACCESSABLE            this.myPrivateMethod(); // NOT ACCESSABLE            this.myPrivateProperty = ""; // NOT ACCESSABLE        }    }}

Page 20: TypeScript Presentation - Jason Haffey

20

TypeScript: The Advance Stuff

Is There More?• Anything written in JavaScript, can be written in TypeScript

• .NET Core• Node.js• Node Package Manager• Etc etc etc etc

• Async/Await - New• Most common JavaScript Frameworks have a Type Definition

• If not, you can create one

function getStringFromWebServerAsync() {    return new Promise<string>((resolve, reject) => {        $.get("http://localhost/GetAString")            .done((data) => {                resolve(data);            })            .fail((err) => {                reject(err);            });    });}

async function asyncExample() {    try {        let data = await getStringFromWebServerAsync();        console.log(data);    }    catch (err) {        console.log(err);    }}

asyncExample();

Page 21: TypeScript Presentation - Jason Haffey

21

Links

• https://en.wikipedia.org/wiki/TypeScript• http://www.typescriptlang.org/• http://vswebessentials.com/• https://github.com/DefinitelyTyped/DefinitelyTyped

Page 22: TypeScript Presentation - Jason Haffey

Code Demo