In this DevMarche very first full english workshop, we'll see how to write/migrate an AngularJS 1.x application to TypeScript. We'll see the best way to implement each angular component (service, controller, directive) using TypeScript. Source code for the samples can be found at this url: https://github.com/AGiorgetti/TechbarAngularsJSTypeScript01
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
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).
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.
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
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’
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!
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
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!
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!
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
- 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.