Learning typescript

download Learning typescript

of 37

  • date post

    15-Jan-2015
  • Category

    Technology

  • view

    1.100
  • download

    0

Embed Size (px)

description

The first deck of a two part learning deck about TypeScript. Here you can view a first introduction to the language and some attention call for some of TypeScript detailes.

Transcript of Learning typescript

  • 1. LEARNINGTypeScriptPART 1 2013, WWW.DIGITALMINDIGNITION.COM, ALEXANDRE MARREIROS

2. LearningAboutAlexandre Marreiros CTO @ INNOVAGENCY Tech Trainner, Speaker & Consultant as IndependentContacts amarreiros@gmail.com @alexmarreiros www.digitalmindignition.com 3. LearningWhat is TypeScriptTypeScript is a superset of Javascript which primarilyprovides static typing, classes and interfaces. One of the bigbenefits is to enable IDEs to provide a richer environment for spottingcommon errors as you type the code. Other benefits can be having all thebest things of javascript in a strong type language. Is also a Codeplexinitiative.Paul DixonTypeScript is a language for application-scale JavaScriptdevelopment.TypeScript is a typed superset of JavaScript that compiles toplain JavaScript. 4. LearningWhy use TypeScriptFor a large Javascript project, adopting Typescript might result inmore robust software, while still being deployable where a regularjavascript application would run.To easy build clean and mantainable code (costum javascriptprogramming can sometimes become messy if you dont applypatterns ).TypeScript allow us to create encapsulation. 5. LearningReview JavaScript Types JavaScript Type System is dynamic Dynamic Type System provide us with: Variables can hold any object Types are determined at the runtime Is impossible to ensure right conversion of types or if the types are passedin the right way, at the development time 6. LearningJavaScript Language Client side language Not compiled Dynamic typed Not Object Oriented Procedure language The mindset of a cliente side language is diferente from the mindset of a server side language. Large enterprise programs need developers to know the two worlds and made that worlds interact to build the aplication experience. 7. LearningTypeScript & JavaScript TypeScript Provide us with: JavaScript Abstration Works on Any Browser Produce Works on Any host Works in Any OSAbstraction Tool SupportIs possible to use standardJavaScript when coding inTypeScript language 8. LearningTypeScript Fundamentals Object OrientedStatic TypingEncapsulationModules ClassesCompiledIntelisense Contructors,LanguageLambdaInterfacesSyntaxFunctions,(Compiles to Functions checkingProperties JavaScript) 9. LearningTypeScript Language first contact CompileClass Message{ Var Message = (function(){innerMsg:string; function Message(msg){ this.innerMsg= msg;constructor(msg:string){ } thid.innerMsg=msg Message.prototype.ShowMSG = } function (){ShowMsg(){ return test + this.innerMsg return test + }innerMsg;return Message}})();}File.tsFile.js 10. LearningTypeScript Language Don t Forget TypeScript is a superste of JavaScript so what issupported by javascript syntax is supported by TypeScript. A scope of a codeblock is limited by {} A codeblock ends with ; All ecma script defined keywords are suported and means thesame in TypeScript 11. LearningTypeScript Languagehttp://weblogs.asp.net/dwahlin/default.aspx 12. Learning TypeScript Language code hierarchy Defines a naming container, that can export Module diferent members 0..*Defines a group of Is a construct that enables you to createbehaviours associated Interface Classyour own custom types.with a concept0..*0..*Fields ConstructorFunctionsMembersProperties Implement Contains 13. Learning Play with TypeScripthttp://www.typescriptlang.org/Playground/ 14. LearningTypeScript Tools support Sublime; Emacs; Vi Visual Studio TypeScript Playground 15. LearningTypeScript SyntaxVariable Declaration: Type inference Var xpto = 2;( declare give a name set value , the type will be infered from the rightoperator parammeter) Type Annotation Var xpto: number = 2;(declare give a name set the type set the value) 16. LearningTypeScript SyntaxVariable Declaration examples: Type inference Var xpto1; xpto1 = test( declare give a name, the type will be infered from the set that is done inthe second line) Var xpto = 2 + this is a test;( declare give a name set value , the type will be infered from the rightoperator parammeter, since the right parameter is a number concat with astring the runtime will assume xpto is a string ) 17. LearningTypeScript SyntaxAmbient Variable Declaration: To get a declared variable of a included file we can use theTypeScript declaredeclare var document(lib.d.ts is referenced by default in TypeScript and has references for theDOM tree and javascript functions)(jquery.d.ts is a file where we can reference the jquery library) 18. LearningTypeScript SyntaxUse variables of other modules and having intellisence: Firt you should have your d.ts file in a known place Second you should reference the file like Third declare the type instance you want to use///declare var $; 19. LearningTypeScript SyntaxThe keyword any Any is the language primitive used to decorate a variable in away that he can assume any type. When you declare a variablelike this no static type validation will be done.var str: any;The keyword null Except void and undefined null is the value who can set any typemeaning theres no value in that instance typeThe keyword undefined Represnts the same as null but with a diferente semanticmean, undefinded says that the variable wasn t iniciated yet 20. LearningTypeScript SyntaxPrimitive Typesany(The Any type is used to represent any JavaScript value. A value of the Any type supports thesame operations as a value in JavaScript and no static type checking)number(The Number primitive type corresponds to the similarly named JavaScript primitive type andrepresents double-precision 64-bit format IEEE 754 floating point values.) string(The String primitive type corresponds to the similarly named JavaScript primitive type andrepresents sequences of characters stored as Unicode UTF-16 code units..) 21. LearningTypeScript SyntaxPrimitive Types null(The Null type is a subtype of all types, except the Void and Undefined types. This means thatnull is considered a valid value for all primitive and object types, including even the Number andBoolean primitive types) undefined(The Undefined type corresponds to the similarly named JavaScript primitive type and is thetype of the undefined literal.)Type Arrays(Represents a container of values of a specific static or dynamic type. In the second case we caillustrate with the following example: var names: string[] = [Antonio,John,Manuel];To ndex the array you use the following notation names[num] ;Where num is the ndex in the array starting at 0 for the first elemento) 22. Learning Play with TypeScripthttp://www.typescriptlang.org/Playground/ 23. LearningTypeScript SyntaxTypeScriptDynamic Approach Static AproachDynamic Typing (type inference) Static TypingEvaluated at runtimeEvaluated at compile time is type safe Just like JavaScript 24. LearningTypeScript SyntaxObject Types Can be functions, class, module, interface, literal Canbe a container of Properties (public or private, required oroptional) call signatures, Contruct Signatures, Index SignaturesExamplesVarVar square:object = {x:100,y:100;}; sum:object=function(first:number, sec: number){return first+sec;}; 25. LearningTypeScript Function Type Declare functions var squareAreaFunc = function (h:number , w:number){return h * w;} Emit the sameJavaScript Using arrow functions var squareAreaFunc = (h:number, w:number) => h*w; Option parameter var Hthere = (str?:string) => alert( name|| no name); Void keywordvar squareAreaFunc = (h:number, w:number) => void; 26. LearningPlay with TypeScript 27. LearningTypscript Interface Functions Interfaces provide the ability to give names to object types andthe ability to compose existing named object types into new ones. Interfaces have no run-time representationthey are purely acompile-time construct. Use the keyword extends to build a interface interface Moverthat extends other interface.{ move(): void; getStatus(): { speed: number; }; }var Moverobj:Mover ={move: function() {.},Declare a interfacegetStatus:function(){}} Implement a interface 28. LearningPlay with TypeScript 29. LearningTypeScript Classes A class is a container His a role is encapsulate code and variables in a encapsolatedconcept 30. LearningTypeScript Classes To define a Classclass Person {} Constructors are used to initialize class instancesIf you use thekeyword public in aClass Person {constructor engine: string;parameter you dont construct (engine : string ){ this.engine = engine;} need to declare thefield} 31. LearningTypeScript Classes Instantiate a new instance of a class var Personinst = new Person (test); Field members in typescript are public by default but we can changethe visibility class Person { private engine:string; } Properties allow you to get or set members valueTypeScript supportsComplexTypes get myEngine:string { return this.engine;} 32. LearningTypeScript Classes Cast between 2 typesvar table: HTMLTableElement = document.createElement(table); TypeScript knowswhat types exist with the reference of type definitionfilesYou can find a lot of type definition files for third party libraries at https://github.com/borisyankov/DefinitelyTyped 33. LearningTypeScript Extending Classes Animalinheritance BirdCat TypeScript defines the keyword extends as a way to allow typesto extend other thypesclass Bird extends Anima{You have toconstructor(){ super();}call the base} class constructor 34. LearningTypeScript Interfaces and Classes TypeScript defines the keyword implements as a way to allowtypes to sign a interface contractclass Bird implements IAnimal .(Note: Consider that IAnimal is a interface that defines thecontract associated to a Animal) The rules to use Interfaces in a Typescript are similar to therules of .NET or JAVA 35. LearningPlay with TypeScript 36. LearningQuestionsYour turn to talk, if you have any questionfeel free to ask 37. LearningReferences http://www.typescriptlang.org/ http://www.typescriptlang.org/Content/TypeScript%20Language%20Spe