KEMBAR78
TypeScript . the JavaScript developer best friend! | PPTX
webnextconf.eu
TypeScript
The JavaScript developer best friend!
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
Agenda
• TypeScript why? what?
• Tooling Setup we need a development environment, right !?!
• The Language (features, futures and pitfalls)
• Q. & A.
Code on GitHub
https://github.com/AGiorgetti/
WebNextConf2015
TypeScript
Why? What?
JavaScript 'the good parts'
• It's a real cross platform language!
• It's everywhere (client side and server side).
• It's easy to learn and to start with!
• It's a dynamic language: flexible and powerful.
• You have 'the freedom' to do whatever you want with
any object.
JavaScript 'the not so good parts'
• It does not have a 'true' type system: how do you check the proper parameter are passed to a
function? (test... Test... Test...)
• Global namespace issues.
• Your code can become messy quickly: lack of maintainability, low code reuse and so on...
• Having a 'relaxed' type system leads to confusion: different equality operators: == support
implicit type conversion, === it does not!
• It can be 'troublesome' for devs used to OO paradigms:
• Lack of class based programming techniques.
• 'New / Unusual' design patterns (prototypical inheritance, revealing module patterns etc...).
• You need to define a code style guide.
• You need to enforce that style guide: it needs discipline!
• It's not well suited for very large [enterprise level] projects:
• It lacks maintainability (code analysis, refactoring)
• It lacks in code structuring (module, classes, …)
• Tooling isn’t good enough!
The good news: JavaScript is evolving! ES6* to the rescue!
* the problem is you cannot have full access to those feature right now! You'll have to wait... and ES5 will be out in the wild for quite some time
anyway...
Sometimes…
JavaScript tooling SUX*!
* I apologize for the chatchphrase to all the Developers that
worked hard to give us the best experience they could.
TypeScript - what is it? why use it?
• 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 (and Classes and Modules)
(+ other goodies).
• Compiles to plain JavaScript (target: ES3, ES5, ES6).
• Any valid JavaScript application is also a TypeScript application.
• Gives us a chance to use new features of the language that will be available in
ES6+ (classes, modules, decorators, etc...: better code structuring and object-
oriented programming techniques).
• Enables BETTER development time tool support (intellisense, syntax checking,
code analysis & navigation, refactoring, documentation).
• Can extend the language beyond the standard (decorators, async/await).
• The best part of it: It's all a development time illusion!
Tooling Setup
we need a development environment, right !?!
Setup TypeScript
You have several ways to install TypeScript (globally
and locally):
http://www.typescriptlang.org/#Download
Editor / IDE
Grab a good code editor
(better with TypeScript support, and provide the proper integration with your task runner of choice)
• Visual Studio 2013, 2015+
• Visual Studio Code
• Webstorm
• Atom
• Sublime
• Eclipse
• …
Editor Setup (Visual Studio Code)
TSC - the TypeScript compiler
TSC is a source-to-source compiler (a transpiler).
There are lots of options that allow you to:
- concatenate different files in a single output file.
- generate sourcemaps.
- generate module loading code (node.js or require.js).
You can play with the TypeScript playground or setup
your environment to see it in action.
tsc app.tsapp.ts app.js
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.
There's a community driven project on GitHub that tracks all
of them:
DefinitelyTyped (http://definitelytyped.org/)
TSD: a specialized package manager to look for definition files
inside DefinitelyTyped repository
(http://definitelytyped.org/tsd/)
Demo
From JavaScript to TypeScript
A quick overview!
Types
number, string, etc... all the standard 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!
type name = : define an alias for a type name.
generics: great for code reuse! We can specify constraints if we want.
Interfaces
Interfaces are used to define the SHAPE of our objects!
They are used to define Contracts within our code!
TypeScript type checking is based on a concept called
Structural Typing (or Duck Typing), which means the
object shape / structure is the most important thing!
Two different interfaces (objects) that expose the same
properties are considered compatible. This mean you can
assign 'apples' to 'oranges' under specific conditions.
Interfaces
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
Classes
Classes implement the behaviors of an entity.
They have support for:
• accessors (get, set) [ES5+]
• modifiers: public, private, protected
• constructor
• inheritable
• static properties
• abstract (class & methods)
• 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)
Classes - Pay Attention to...
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!
Namespace & Module
• Namespaces and Modules are used to add more
structuring to your code.
• Group and Organize objects based on their
behavior or because they are related to each other
in some way (i.e.: all the classes of a specific
feature, a library, etc...).
• Allow to split your code in multiple files.
Namespace
Also called 'internal module':
• export: decide what to expose to the outside world.
• can be split in multiple files.
How to use:
• build the whole application concatenating all the files.
• reference the files using <script> tags in the correct
order.
NO DYNAMIC MODULE LOADING (Node.js / Require.js)
Module
Also called 'external module':
• export: decide what to expose to the outside world.
• have file scope! (map 1:1 with the files that define it).
• any file containing a top-level import or export is considered
a module.
• must use the '--module' compiler switch [commonjs, AMD,
system, ...].
How to use:
• Reference them using the 'import' keyword and assign a
name alias.
• Node.js / Require.js dynamic module loaders.
Decorators (ES7 proposal)
Decorators make it possible to annotate and modify classes and properties at
design time.
A decorator is:
• an expression
• that evaluates to a function
• that takes the target, name, and property descriptor as arguments
• and optionally returns a property descriptor to install on the target object
In TypeScript we have 4 types of decorators:
• ClassDecorator
• MethodDecorator
• PropertyDecorator
• ParameterDecorator
Various / Advanced
TypeScript also has
support for many more
ES6 features:
• Let / const
• Destructuring
declarations
• For..of
• Template strings
• Generators
• Class expressions
And some language
specific / custom
extensions:
• Tuple types
• Union types
• Intersection types
• Decorators (ES7
proposal)
• Async / await
What's Next?
Roadmap:
https://github.com/Microsoft/TypeScript/wiki/Road
map
Thanks All!
I hope you enjoyed the session!
Let’s stay in touch!
Q. & A.
"Speak now or forever hold your peace!"
License
This work is published under:
Creative Commons
Attribution NonCommercial ShareAlike 3.0
License
http://creativecommons.org/licenses/by-nc-sa/3.0/

TypeScript . the JavaScript developer best friend!

  • 1.
  • 2.
  • 3.
    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
  • 4.
    Agenda • TypeScript why?what? • Tooling Setup we need a development environment, right !?! • The Language (features, futures and pitfalls) • Q. & A.
  • 5.
  • 6.
  • 7.
    JavaScript 'the goodparts' • It's a real cross platform language! • It's everywhere (client side and server side). • It's easy to learn and to start with! • It's a dynamic language: flexible and powerful. • You have 'the freedom' to do whatever you want with any object.
  • 8.
    JavaScript 'the notso good parts' • It does not have a 'true' type system: how do you check the proper parameter are passed to a function? (test... Test... Test...) • Global namespace issues. • Your code can become messy quickly: lack of maintainability, low code reuse and so on... • Having a 'relaxed' type system leads to confusion: different equality operators: == support implicit type conversion, === it does not! • It can be 'troublesome' for devs used to OO paradigms: • Lack of class based programming techniques. • 'New / Unusual' design patterns (prototypical inheritance, revealing module patterns etc...). • You need to define a code style guide. • You need to enforce that style guide: it needs discipline! • It's not well suited for very large [enterprise level] projects: • It lacks maintainability (code analysis, refactoring) • It lacks in code structuring (module, classes, …) • Tooling isn’t good enough! The good news: JavaScript is evolving! ES6* to the rescue! * the problem is you cannot have full access to those feature right now! You'll have to wait... and ES5 will be out in the wild for quite some time anyway...
  • 9.
    Sometimes… JavaScript tooling SUX*! *I apologize for the chatchphrase to all the Developers that worked hard to give us the best experience they could.
  • 10.
    TypeScript - whatis it? why use it? • 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 (and Classes and Modules) (+ other goodies). • Compiles to plain JavaScript (target: ES3, ES5, ES6). • Any valid JavaScript application is also a TypeScript application. • Gives us a chance to use new features of the language that will be available in ES6+ (classes, modules, decorators, etc...: better code structuring and object- oriented programming techniques). • Enables BETTER development time tool support (intellisense, syntax checking, code analysis & navigation, refactoring, documentation). • Can extend the language beyond the standard (decorators, async/await). • The best part of it: It's all a development time illusion!
  • 11.
    Tooling Setup we needa development environment, right !?!
  • 12.
    Setup TypeScript You haveseveral ways to install TypeScript (globally and locally): http://www.typescriptlang.org/#Download
  • 13.
    Editor / IDE Graba good code editor (better with TypeScript support, and provide the proper integration with your task runner of choice) • Visual Studio 2013, 2015+ • Visual Studio Code • Webstorm • Atom • Sublime • Eclipse • …
  • 14.
  • 15.
    TSC - theTypeScript compiler TSC is a source-to-source compiler (a transpiler). There are lots of options that allow you to: - concatenate different files in a single output file. - generate sourcemaps. - generate module loading code (node.js or require.js). You can play with the TypeScript playground or setup your environment to see it in action. tsc app.tsapp.ts app.js
  • 16.
    TSD - TypeScriptDefinition 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. There's a community driven project on GitHub that tracks all of them: DefinitelyTyped (http://definitelytyped.org/) TSD: a specialized package manager to look for definition files inside DefinitelyTyped repository (http://definitelytyped.org/tsd/)
  • 17.
    Demo From JavaScript toTypeScript A quick overview!
  • 18.
    Types number, string, etc...all the standard 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! type name = : define an alias for a type name. generics: great for code reuse! We can specify constraints if we want.
  • 19.
    Interfaces Interfaces are usedto define the SHAPE of our objects! They are used to define Contracts within our code! TypeScript type checking is based on a concept called Structural Typing (or Duck Typing), which means the object shape / structure is the most important thing! Two different interfaces (objects) that expose the same properties are considered compatible. This mean you can assign 'apples' to 'oranges' under specific conditions.
  • 20.
    Interfaces 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
  • 21.
    Classes Classes implement thebehaviors of an entity. They have support for: • accessors (get, set) [ES5+] • modifiers: public, private, protected • constructor • inheritable • static properties • abstract (class & methods) • 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)
  • 22.
    Classes - PayAttention to... 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!
  • 23.
    Namespace & Module •Namespaces and Modules are used to add more structuring to your code. • Group and Organize objects based on their behavior or because they are related to each other in some way (i.e.: all the classes of a specific feature, a library, etc...). • Allow to split your code in multiple files.
  • 24.
    Namespace Also called 'internalmodule': • export: decide what to expose to the outside world. • can be split in multiple files. How to use: • build the whole application concatenating all the files. • reference the files using <script> tags in the correct order. NO DYNAMIC MODULE LOADING (Node.js / Require.js)
  • 25.
    Module Also called 'externalmodule': • export: decide what to expose to the outside world. • have file scope! (map 1:1 with the files that define it). • any file containing a top-level import or export is considered a module. • must use the '--module' compiler switch [commonjs, AMD, system, ...]. How to use: • Reference them using the 'import' keyword and assign a name alias. • Node.js / Require.js dynamic module loaders.
  • 26.
    Decorators (ES7 proposal) Decoratorsmake it possible to annotate and modify classes and properties at design time. A decorator is: • an expression • that evaluates to a function • that takes the target, name, and property descriptor as arguments • and optionally returns a property descriptor to install on the target object In TypeScript we have 4 types of decorators: • ClassDecorator • MethodDecorator • PropertyDecorator • ParameterDecorator
  • 27.
    Various / Advanced TypeScriptalso has support for many more ES6 features: • Let / const • Destructuring declarations • For..of • Template strings • Generators • Class expressions And some language specific / custom extensions: • Tuple types • Union types • Intersection types • Decorators (ES7 proposal) • Async / await
  • 28.
  • 30.
    Thanks All! I hopeyou enjoyed the session! Let’s stay in touch!
  • 31.
    Q. & A. "Speaknow or forever hold your peace!"
  • 32.
    License This work ispublished under: Creative Commons Attribution NonCommercial ShareAlike 3.0 License http://creativecommons.org/licenses/by-nc-sa/3.0/

Editor's Notes

  • #8 Our story / relationship with JavaScript began when we decided how to develop the next version of our signature application, we decided to go for: - microservices - DDD / CQRS  / ES - web front end<- it turned out that with the same technologies we could also create stand alone apps.
  • #11 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!
  • #13 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​
  • #18 Let's consider a typical situation
  • #20 Interfaces are used to define the SHAPE of our objects!​ Interface IPersonalData{​    Id: number,​    Name: string,​    ...​ }​ ​ An Interface can describe a function:​ interface loggingFunction{​ (message: string): void​ }​ An Interface can describe an array / dictionary:​ interface StringDictionary {​ [index: string]: string; // index can be number or string​ }​ ​ An Interface can describe an hybrid type:​ interface Timer {​ (interval: number): string;​ interval: number;​ reset(): void;​ }​ ​ ​