SlideShare ist ein Scribd-Unternehmen logo
1 von 41
AngularJs and TypeScript
the 'right' way!
some best practices for writing an AngularJs 1.x application using
TypeScript
Alessandro Giorgetti
www.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.alessandro
Twitter: @a_giorgetti
LinkedIn: https://it.linkedin.com/in/giorgettialessandro
E-mail: alessandro.giorgetti@live.com
Blog: www.primordialcode.com
The Code is here!
https://github.com/AGiorgetti/TechbarAngularsJSTypeScript01
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
How much productive are you
when writing an Angular
application?
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Is it easy to maintain and refactor
your Angular application?
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Are your tools supporting you
properly?
Alessandro Giorgetti
www.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
The Starting Point
An AngularJS ToDo list application.
Alessandro Giorgetti
www.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).
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Hands on... JavaScript
Get 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
Why TypeScript ?
Introduction, setup and usage
Alessandro Giorgetti
www.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?
Alessandro Giorgetti
www.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.
Alessandro Giorgetti
www.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!
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Types
number, 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.
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Interfaces
An 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
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Classes
Classes 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)
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Type checking: Structural Typing /
Duck Typing
Interfaces 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."
Alessandro Giorgetti
www.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!
Alessandro Giorgetti
www.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!
Alessandro Giorgetti
www.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.
Hands-on: Setup the
Environment
- install Node, Visual Studio Code and TypeScript.
- configure the project and Visual Studio Code to
compile TypeScript files.
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Setup TypeScript
You have several ways to install TypeScript (globally
and locally):
http://www.typescriptlang.org/#Download
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Requirements
You 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.json
Install TSD
- globally: npm install tsd -g
Get the code:
git checkout step01-js
Alessandro Giorgetti
www.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 libraries
tsd install express -save
tsd install bootstrap -save
tsd install angular -save
tsd install angular-route -save
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Setup the Project and VSCode
- ensure everything is updated:
tsd update -s -o
tsd rebundle
ncu --upgradeAll
npm 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.
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Setup the Project and VSCode
Optional, 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
Hands-on: let's change
legacy JavaScript code
to 'proper' TypeScript!
Time to do the dirty job!
Alessandro Giorgetti
www.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.
Alessandro Giorgetti
www.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
Alessandro Giorgetti
www.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
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Service [implement them using a class]
Alessandro Giorgetti
www.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’
Alessandro Giorgetti
www.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
Alessandro Giorgetti
www.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!
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
In terms of dev experience…
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Controller [mplement them using a class]
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Directive [implement them using a function…]
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Directive […or a class, but I do not recommend this approach]
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Thanks All!
I hope you enjoyed the session!
Let’s stay in touch!
Alessandro Giorgetti
www.primordialcode.comdev.marche.it
Fix the samples!
Fix the jsconfig.json
Add 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.js
I 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.

Weitere ähnliche Inhalte

Mehr von Alessandro Giorgetti

The Big Picture - Integrating Buzzwords
The Big Picture - Integrating BuzzwordsThe Big Picture - Integrating Buzzwords
The Big Picture - Integrating BuzzwordsAlessandro Giorgetti
 
AngularConf2016 - A leap of faith !?
AngularConf2016 - A leap of faith !?AngularConf2016 - A leap of faith !?
AngularConf2016 - A leap of faith !?Alessandro Giorgetti
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!Alessandro Giorgetti
 
«Real Time» Web Applications with SignalR in ASP.NET
«Real Time» Web Applications with SignalR in ASP.NET«Real Time» Web Applications with SignalR in ASP.NET
«Real Time» Web Applications with SignalR in ASP.NETAlessandro Giorgetti
 
DNM19 Sessione1 Orchard Primo Impatto (ita)
DNM19 Sessione1 Orchard Primo Impatto (ita)DNM19 Sessione1 Orchard Primo Impatto (ita)
DNM19 Sessione1 Orchard Primo Impatto (ita)Alessandro Giorgetti
 
DNM19 Sessione2 Orchard Temi e Layout (Ita)
DNM19 Sessione2 Orchard Temi e Layout (Ita)DNM19 Sessione2 Orchard Temi e Layout (Ita)
DNM19 Sessione2 Orchard Temi e Layout (Ita)Alessandro Giorgetti
 

Mehr von Alessandro Giorgetti (7)

The Big Picture - Integrating Buzzwords
The Big Picture - Integrating BuzzwordsThe Big Picture - Integrating Buzzwords
The Big Picture - Integrating Buzzwords
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
AngularConf2016 - A leap of faith !?
AngularConf2016 - A leap of faith !?AngularConf2016 - A leap of faith !?
AngularConf2016 - A leap of faith !?
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!
 
«Real Time» Web Applications with SignalR in ASP.NET
«Real Time» Web Applications with SignalR in ASP.NET«Real Time» Web Applications with SignalR in ASP.NET
«Real Time» Web Applications with SignalR in ASP.NET
 
DNM19 Sessione1 Orchard Primo Impatto (ita)
DNM19 Sessione1 Orchard Primo Impatto (ita)DNM19 Sessione1 Orchard Primo Impatto (ita)
DNM19 Sessione1 Orchard Primo Impatto (ita)
 
DNM19 Sessione2 Orchard Temi e Layout (Ita)
DNM19 Sessione2 Orchard Temi e Layout (Ita)DNM19 Sessione2 Orchard Temi e Layout (Ita)
DNM19 Sessione2 Orchard Temi e Layout (Ita)
 

Kürzlich hochgeladen

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 

Kürzlich hochgeladen (20)

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 

Techbar Angular and TypeScript: the 'right' way!

  • 1. AngularJs and TypeScript the 'right' way! some best practices for writing an AngularJs 1.x application using TypeScript
  • 2. Alessandro Giorgetti www.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.alessandro Twitter: @a_giorgetti LinkedIn: https://it.linkedin.com/in/giorgettialessandro E-mail: alessandro.giorgetti@live.com Blog: www.primordialcode.com
  • 3. The Code is here! https://github.com/AGiorgetti/TechbarAngularsJSTypeScript01
  • 4. Alessandro Giorgetti www.primordialcode.comdev.marche.it How much productive are you when writing an Angular application?
  • 5. Alessandro Giorgetti www.primordialcode.comdev.marche.it Is it easy to maintain and refactor your Angular application?
  • 7. Alessandro Giorgetti www.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
  • 8. The Starting Point An AngularJS ToDo list application.
  • 9. Alessandro Giorgetti www.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).
  • 10. Alessandro Giorgetti www.primordialcode.comdev.marche.it Hands on... JavaScript Get 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
  • 12. Alessandro Giorgetti www.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?
  • 13. Alessandro Giorgetti www.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.
  • 14. Alessandro Giorgetti www.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!
  • 15. Alessandro Giorgetti www.primordialcode.comdev.marche.it Types number, 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.
  • 16. Alessandro Giorgetti www.primordialcode.comdev.marche.it Interfaces An 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
  • 17. Alessandro Giorgetti www.primordialcode.comdev.marche.it Classes Classes 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)
  • 18. Alessandro Giorgetti www.primordialcode.comdev.marche.it Type checking: Structural Typing / Duck Typing Interfaces 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."
  • 19. Alessandro Giorgetti www.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!
  • 20. Alessandro Giorgetti www.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!
  • 21. Alessandro Giorgetti www.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.
  • 22. Hands-on: Setup the Environment - install Node, Visual Studio Code and TypeScript. - configure the project and Visual Studio Code to compile TypeScript files.
  • 23. Alessandro Giorgetti www.primordialcode.comdev.marche.it Setup TypeScript You have several ways to install TypeScript (globally and locally): http://www.typescriptlang.org/#Download
  • 24. Alessandro Giorgetti www.primordialcode.comdev.marche.it Requirements You 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.json Install TSD - globally: npm install tsd -g Get the code: git checkout step01-js
  • 25. Alessandro Giorgetti www.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 libraries tsd install express -save tsd install bootstrap -save tsd install angular -save tsd install angular-route -save
  • 26. Alessandro Giorgetti www.primordialcode.comdev.marche.it Setup the Project and VSCode - ensure everything is updated: tsd update -s -o tsd rebundle ncu --upgradeAll npm 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.
  • 27. Alessandro Giorgetti www.primordialcode.comdev.marche.it Setup the Project and VSCode Optional, 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
  • 28. Hands-on: let's change legacy JavaScript code to 'proper' TypeScript! Time to do the dirty job!
  • 29. Alessandro Giorgetti www.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.
  • 30. Alessandro Giorgetti www.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
  • 31. Alessandro Giorgetti www.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
  • 33. Alessandro Giorgetti www.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’
  • 34. Alessandro Giorgetti www.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
  • 35. Alessandro Giorgetti www.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!
  • 39. Alessandro Giorgetti www.primordialcode.comdev.marche.it Directive […or a class, but I do not recommend this approach]
  • 40. Alessandro Giorgetti www.primordialcode.comdev.marche.it Thanks All! I hope you enjoyed the session! Let’s stay in touch!
  • 41. Alessandro Giorgetti www.primordialcode.comdev.marche.it Fix the samples! Fix the jsconfig.json Add 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.js I 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.

Hinweis der Redaktion

  1. TypeScript = JavaScript + Static Types +Code Encapsulation (Modularity) There are also other approaches: Dart / CoffeeScript other languages that compile to JavaScript too. Every language is just a layer on top of another layer (on top of another layer) down to the assembly code!
  2. TypeScript = JavaScript + Static Types +Code Encapsulation (Modularity) There are also other approaches: Dart / CoffeeScript other languages that compile to JavaScript too. Every language is just a layer on top of another layer (on top of another layer) down to the assembly code!
  3. if you intall it manually: install Node.js (https://nodejs.org/en/)​ from a console prompt: npm install -g typescript​ check for the proper version to be installed (tsc -v) eventually fix the path environment variables​
  4. - edit package.json -> add typescript files. npm install -> download new packages. - tsd: add some libraries tsd install express -save tsd install bootstrap -save (will also install jquery) tsd install angular -save tsd install angular-route -save - ensure everything is updated: tsd update -s -o tsd rebundle ncu --upgradeAll npm install - edit gulpfile.js -> add TypeScript compilation steps. - edit tasks.json -> show how to make accessible the new typescript tasks. - place a tsconfig.json file on the root VSCode will internally pick that and use it. This way any .ts and .d.ts will be read and compiled and there will be no need to add /// <reference path="tsd.d.ts" /> all around.