techbar angular and typescript: the 'right' way!

41
AngularJs and TypeScript the 'right' way! some best practices for writing an AngularJs 1.x application using TypeScript

Upload: alessandro-giorgetti

Post on 09-Jan-2017

452 views

Category:

Software


1 download

TRANSCRIPT

Page 1: Techbar Angular and TypeScript: the 'right' way!

AngularJs and TypeScriptthe 'right' way!

some best practices for writing an AngularJs 1.x application using TypeScript

Page 2: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Who Am I ?Alessandro Giorgetti

co-owner: SID s.r.l.co-founder: DotNetMarche, DevMarche

Facebook: https://www.facebook.com/giorgetti.alessandroTwitter: @a_giorgetti

LinkedIn: https://it.linkedin.com/in/giorgettialessandroE-mail: [email protected]

Blog: www.primordialcode.com

Page 3: Techbar Angular and TypeScript: the 'right' way!

The Code is here!

https://github.com/AGiorgetti/TechbarAngularsJSTypeScript01

Page 4: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

How much productive are you when writing an Angular

application?

Page 5: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Is it easy to maintain and refactor your Angular application?

Page 6: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Are your tools supporting you properly?

Page 7: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Agenda• The Starting Point

an AngularJs application written in JavaScript.

• Why TypeScript ? Types, Interfaces and Classes, Namespace and Modules!Help us structuring the application!

Help the tools provide us more information!

• Hands-on: configure the environment for TypeScript a quick introduction, setup and usage.

• Hands-on: let's migrate that legacy JavaScript code to 'proper' TypeScript code!Write an Angular app with TypeScript:• Service• Controller• Directive

Page 8: Techbar Angular and TypeScript: the 'right' way!

The Starting Point

An AngularJS ToDo list application.

Page 9: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

You should write Angular code keeping in mind...The purpose:Writing and Angular 1.x application using a coding style that will make it easy for us to:• Migrate every component to TypeScript.• Migrate every component to Angular 2.

Key points:- register components using '.service()' instead of '.factory()'(define components that need to be created with the 'new' operator).- bind the controllers using the 'controllerAs' syntax.- know what changes when dealing with the $scope object(bindToController).

Page 10: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Hands on... JavaScriptGet the code:git checkout step01-js

Open Visual Studio Code and run the App:http://localhost:3000/build/index.html

Take a look at:- express webservice- service- controller- directive

Page 11: Techbar Angular and TypeScript: the 'right' way!

Why TypeScript ?Introduction, setup and usage

Page 12: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Drawbacks of JavaScript code...• Lack of Code Structuring / Coherence:

• Many different styles of writing JavaScript code.• Lack of Object Oriented design paradigms and class based programming techniques. • 'New / Unusual' design patterns (prototypical inheritance, revealing module patterns etc...). • You need to define a coding style guide. • You need to enforce that style guide: it needs discipline!

• No type checking!• More tests to catch trivial errors.• No way to ‘enforce’ code contracts or constraints.• Code is not self-documented: you NEED better documentation.

• Tooling isn’t good enough!• No (or very poor) code analysis.• No type checking.• Very poor refactoring support.• Intellisense ? Can you trust it ?• Code navigation ? Are you really still using string search?

Page 13: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Introducing TypeScript • It's an Open Source project from Microsoft Technologies.

• An attempt to 'fix' the missing parts of JavaScript.

• A Superset of JavaScript => JavaScript + Static Types + Code Structuring.

• TypeScript is a Source to Source compiler: a transpiler.

• It uses ES2015 syntax with Type Annotation and compiles to plain JavaScript (target: ES3, ES5, ES6).

• Any valid JavaScript application is also a TypeScript application.

Page 14: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

TypeScript Helps us to:

• Structure our code (types, interfaces, classes, namespaces and modules).• Use object-oriented programming paradigms and techniques.• Enforce coding guidelines.

Delivers a better Coding Experience:• Intellisense.• Syntax checking.• Code Analysis & Navigation.• Refactoring.• Documentation.

Gets us ready for Angular 2.0.

The best part of it: It's all a development time illusion!

Page 15: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Typesnumber, string, etc... all the primitive JavaScript Types.

any: I can be any type, disable the type checking!

void: I have no type at all (function return value)!

enum / const enum: define enumerated values.

<T>: casting! This is not a type conversion!

Generics: great for code reuse! We can specify constraints if we want.

Page 16: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

InterfacesAn interface defines a contract in your code, the shape of an entity.

Interfaces can describe:• Objects• Functions• Arrays / Dictionaries• Hybrid Types ('things' that are both objects and functions)

Interfaces support:• Inheritance

They do not support accessors (get / set): you need to convert the 'property' to a 'getProperty()' function if you wanna give that readonly behavior

Page 17: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

ClassesClasses implement the behaviors of an entity, it brings the entity to life.

They have support for:• accessors (get, set) [ES5+]• modifiers: public, private, protected• constructor• inheritable• static properties• abstract (class & methods)• method overload (but the way you do it is just... ugly!)• interface implementation

Classes also define Types, they have two sides:• instance side (the properties involved in structural type checking)• static side (constructor and static properties, not involved in the type checking)

Page 18: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Type checking: Structural Typing / Duck TypingInterfaces and Classes are used to define new Types!

The shape of an object (its properties and functions) matters!

"Two different objects (interfaces, classes) that expose the same properties are considered compatible."

Page 19: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Keep in mind 'this'! It is super-important!The 'this': most of the times it represents the instance of the class itself (like in C#). The 'this' has a different meaning in function expression and when using the 'arrow syntax': • function() { … }: this act exactly as expected in strict mode (it can be

undefined or whatever it was when entering the function execution context).

• () => { … }: this always refers to the class instance. Composition / Encapsulation patterns: don't mess up with the this! Always delegate the function call properly, that is: call the function on its original object rather than assigning the pointer to the function to another variable!

Page 20: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Takeaway:• Duck Typing: the shape matters!

• Always use the 'arroy syntax' when defining functions on the fly!

• Composition (the same in JavaScript): always call the function on its original object instance, never assign the pointer to another variable!

Page 21: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

TSD - TypeScript Definition Files package manager

TypeScript Definition File (ambient declaration file)• .d.ts extension.• Allows the definition of strong types.• Provide type definition for external JavaScript libraries.

DefinitelyTyped (http://definitelytyped.org/):a community driven project on GitHub that tracks all of them.

TSD: a specialized package manager to look for definition files inside DefinitelyTyped repository.

Page 22: Techbar Angular and TypeScript: the 'right' way!

Hands-on: Setup the Environment

- install Node, Visual Studio Code and TypeScript.- configure the project and Visual Studio Code to

compile TypeScript files.

Page 23: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Setup TypeScriptYou have several ways to install TypeScript (globally and locally): http://www.typescriptlang.org/#Download

Page 24: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

RequirementsYou should already have:- Node (https://nodejs.org)- Visual Studio Code (https://code.visualstudio.com/)

Install TypeScript- globally: npm install typescript -g- locally to the project: package.jsonInstall TSD- globally: npm install tsd -g

Get the code: git checkout step01-js

Page 25: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Setup the Project and VSCode- edit package.json -> add the typescript packages (version number might change):"typescript": "^1.7.5""gulp-typescript": "^2.10.0""tslint": "^3.3.0""gulp-tslint": "^4.3.1"npm install -> download new packages.

- tsd: add some librariestsd install express -savetsd install bootstrap -savetsd install angular -savetsd install angular-route -save

Page 26: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Setup the Project and VSCode- ensure everything is updated:tsd update -s -otsd rebundlencu --upgradeAllnpm install

- edit gulpfile.js -> add TypeScript compilation steps.

- edit tasks.json -> export the new typescript tasks to VSCode.

- place a tsconfig.json file on the root folder, VSCode will internally pick that and use it. This way any '.ts' and '.d.ts' file will be read and compiled without the need to add /// <reference path="tsd.d.ts" /> all around.

Page 27: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Setup the Project and VSCodeOptional, but recommended:

- configure tslint with a tslint.json file specifying which rules you want to enforce. It will help define and enforce a common style guide for the team.

I always like to set:"no-trailing-whitespace": false,"quotemark": [true, "double"],

Get the fully configured environment: git checkout step03-ts

Page 28: Techbar Angular and TypeScript: the 'right' way!

Hands-on: let's change legacy JavaScript code to 'proper' TypeScript!

Time to do the dirty job!

Page 29: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Angular favors:• Separation of Concerns.• Code Structuring (module, service, controller,

directive).• Dependency Injection!

TypeScript is all about:• Code Structuring (interface, class, namespace,

module).• Better tooling / development experience.

Page 30: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Angular - concepts TypeScript – best implemented with

Business Entities interface, class

Service interface, class

Controller class (possibly with an interface)

Directive function

Page 31: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Let's do it...Get the code: git checkout step04-ts

As a reference I will attach some slides from my previous session at the italian AngularJs Conference 2015 in which I did show how to migrate an application from JavaScript to TypeScript.I know: I am lazy! :D

Page 32: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Service [implement them using a class]

Page 33: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Service [Class declaration and constructor]

A generic ‘function’ becomes a ‘class’

An initialization function becomes the constructor

Dependency injection is specified with a static property

Usage of arrow functions to properly manage the ‘this’

Page 34: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Service [define member functions]

No need to use the ‘function’ keyword.No need to specify ‘this.’: functions already belongs to the class.

1) Creates an ‘instance’ function.

2) Creates a ‘prototype’ function.

1

2

Page 35: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Remember 'this' ?The 'this': most of the times it represents the instance of the class itself (like in C#).

The 'this' has a different meaning in function expression and when using the 'arrow syntax':

• function() { … }: this act exactly as expected in strict mode (it can be undefined or whatever it was when entering the function execution context).

• () => { … }: this always refers to the class instance.

Composition / Encapsulation patterns: don't mess up with the this! Always delegate the function call properly, that is: call the function on its original object rather than assigning the pointer to the function to another variable!

Page 36: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

In terms of dev experience…

Page 37: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Controller [mplement them using a class]

Page 38: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Directive [implement them using a function…]

Page 39: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Directive […or a class, but I do not recommend this approach]

Page 40: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Thanks All!

I hope you enjoyed the session!

Let’s stay in touch!

Page 41: Techbar Angular and TypeScript: the 'right' way!

Alessandro Giorgettiwww.primordialcode.comdev.marche.it

Fix the samples!Fix the jsconfig.jsonAdd the right exclude paths, otherwise whenever you build the application even the files inside the 'build' artifact folder will be compiled by the editor.

The fix is:

"exclude": [

"./build",

"./typings",

"build",

"typings"

]

Fix the Gullpfile.jsI forgot the 'return' statement on all the gulp tasks, without that operations in every task are run concurrently (if you have task that depends on them they will be started in the correct order, but gulp will not wait for the dependent task to end):

http://stackoverflow.com/questions/24619290/making-gulp-write-files-synchronously-before-moving-on-to-the-next-task

The fix is:

- Add a 'return' statement to every task.