KEMBAR78
4Developers: Tomasz Ducin- JavaScript + Java = TypeScript | PDF
Tomasz Ducin
11th April 2016, Warsaw
JavaScript + Java
= TypeScript
Tomasz Ducin
JavaScript, Java, Python
senior software consultant @ Cybercom Poland
trainer @ Bottega IT Solutions
blah, blah, blah...
@tomasz_ducin
ducin
ducin.it
Agenda
1. a glance at TS
2. JS tooling landscape
3. TypeScript - and the problems:
solved & unsolved
4. JS , ES6, TS, CS
5. TS: profit and loss
TypeScript
experienced?
Are you
private customer banking interface
TypeScript-based 
1+ year to go on production
deployed on 120+ Scandinavian banks
PortalBank
massive fake data generator
based on:
JSON Schema
faker.js, chance.js
started in 2014
rewritten to TS in 2016, v0.3
json-schema-faker.js.org
github.com/json-schema-faker/json-schema-faker
function objectRange<T>(obj: T, times: number): T[] {
  var result: T[] = []; 
  for (var i = 0; i < times; i++) { 
    result.push(obj); 
  } 
  return result; 
}
module cash {   
  export interface Payment { 
    amount: number; 
    account: string; 
  } 
} 
TS playground link (above code)
function objectRange<T>(obj: T, times: number): T[];
module cash {   
  export interface Payment { 
    amount: number; 
    account: string; 
  } 
}
TS playground link (above code)
var payments = objectRange<cash.Payment>({
    "amount":12.34, 
    "account": "1234 5678 90" 
}, 5); 
console.log(payments); 
JavaScript Java
weak typing
asynchronous,
single-threaded
functional
programming
prototype-based
both clients and servers
strong typing
synchronous/parallel
mainly
object oriented
programming
class-based
server-side
TypeScript
strong typing
asynchronous,
single-threaded
functional
programming
both clients and servers
object oriented
programming
class-based
+
=
JavaScript Fatigue
xx x x
“ think about the
problems you
solve,
NOT the tools
problems TS   solves
1. checks types
                                
test.ts(5,5): error TS2345: Argument of type 'string'
  is not assignable to parameter of type 'number'.
problems TS   solves
3. less unit tests
                              
assert.isString 
assert.isNumber 
assert.isBoolean
problem exists in all weakly-typed languages
2. less runtime bugs
problems TS   solves
4. low-level refactoring
CORE
M1 M2 M3 change or
extend
problems TS   solves
5. reduces JS pitfalls
                                
// JS 
var a = 4; 
var b = 5; 
var c = a * b; 
// c == 20
                                
// JS 
var a = "hello";
var b = "world";
var c = a * b; 
// c == NaN
                                
// TS 
var a: string = "hello"; 
var b: string = "world"; 
var c: string = a * b; 
                                
// TS 
var a = "hello"; 
var b = "world"; 
var c = a * b; 
                                
test.ts(4,5): error TS2322: Type 'number' is not assignable to 
  type 'string'. 
test.ts(4,17): error TS2362: The left­hand side of an arithmetic 
  operation must be of type 'any', 'number' or an enum type. 
test.ts(4,21): error TS2363: The right­hand side of an arithmetic
  operation must be of type 'any', 'number' or an enum type.
problems TS   solves
6. disables JS hacks
                                
var mod = null; 
function logic(){...} 
module.exports = function(){ 
  mod = mod || require('MODULE');
  return logic.apply(...); 
}
?
problems TS   solves
7. native modules
                                
module outer { 
  var str = "hello world"; 
  module inner { 
    var num = 6; 
  } 
}
                                
var outer; 
(function (outer) { 
    var str = "hello world"; 
    var inner; 
    (function (inner) { 
        var num = 6; 
    })(inner || (inner = {})); 
})(outer || (outer = {})); 
problems TS   solves
8. big business logic
under control
Design
Patterns
Domain
Driven
Design
DDD: Value Objects
CORE
M1 M2 M3 extend base
object
                                
var price = 7.99;
                                
var price = { 
  amount: 7.99, 
  currency: "PLN" 
};
DDD: Value Objects
                                
declare type price = number;
interface Price { 
  amount: number; 
}                        
interface Price { 
  amount: number; 
  currency: string; 
}
Communication Contract
Data Transfer Objects
                                
// GET /customers/{id}
                                
interface Customer { 
  firstName: string; 
  lastName: string; 
  age: number; 
}
Data Transfer Objects
Data Transfer Objects
                                
// GET /customers 
// GET /customers/{id}
                                
interface Customer { 
  firstName: string; 
  lastName: string; 
  age: number; 
} 
declare type CustomerList = Customer[];
Data Transfer Objects
                                
// GET /customers 
// GET /customers/{id} 
// GET /customers/{id}/addresses
                                
interface Address { 
  street: string; 
  city: string; 
  country: string; 
}
                            
interface Customer { 
  ... 
  addresses: Address[]; 
}
Data Transfer Objects
                                
getAsyncData({ 
  url: "/customers/<id>" 
  method: "GET", 
  ... 
}, function(customer: Customer): void { 
  process(customer.firstName); // ok 
  process(customer.lastName); // ok 
  process(customer.name); // ERROR!!! 
});
problems TS  doesn't solve
1. mistakes
logical mistakes
lack of knowledge
asynchronous errors
(e.g. race conditions)
problems TS  doesn't solve
2. still need to understand JS
writing TS without
knowing JS == disaster
what output will TS
provide?
read code in terms of
both: OOP and async
runtime
problems TS  doesn't solve
3. won't make it faster
won't make you code faster
won't make app run faster
actually, will slow both down
just a little bit
TS might produce more code
than pure JS (modules, classes)
problems TS  doesn't solve
4. the any type
stands for NO TYPE
very easy to use
very messy to use
it's very tempting
sometimes just can't do without
will spoil your app if used in big amounts
just like donuts...
“ nothing comes
for free
problems TS introduces
1. automation becomes
more expensive
need to transpile TS
down to JS
big project = big cost
blockers included
problems TS introduces
2. compatibility with
3rd party libs
DefinitelyTyped
less popular projects
lack .d.ts files
problems TS introduces
3. your teammates need to learn
probably you'll teach them
entry level is quite low
problems TS introduces
4. debugging less convenient
browsers don't execute TS
source and output: different
writing JavaScript is
not trendy anymore ;)
when is it worth to go TS?
project size? people?
“ all decisions
have pros and
cons
transpiling JS
pros & cons
more features
might be less code
efficiency
following trends
more code complexity
higher entry-level
for BE & junior devs
IDE support needed
more setup complex
value of the
new features
costs of
introducing it>
?
“ think about the problems you
solve, NOT the tools
“ always be responsible for the
tools you introduce
“ nothing comes for free
“ all decisions have pros
and cons
THX!
@tomasz_ducin
4  Q&A
tomasz@ducin.it
writing JavaScript is
not trendy anymore ;)
ES6arrows
classes
enhanced object literals
template strings
destructuring
default + rest + spread
let + const
iterators + for..of
generators
unicode
modules
module loaders
map + set + weakmap + weakset
proxies
symbols
subclassable built-ins
promises
math + number + string + array + object APIs
binary and octal literals
reflect api
tail calls
TypeScript
most of what ES6 has
type checks
templates typecheck
( ongoing)
TS -> ES6 (ongoing)
CoffeeScript syntax
# Assignment: 
number   = 42 
opposite = true 
# Conditions: 
number = ­42 if opposite 
# Functions: 
square = (x) ­> x * x 
# Arrays: 
list = [1, 2, 3, 4, 5]
var list, number, opposite, square;
number = 42; 
opposite = true; 
if (opposite) { 
  number = ­42; 
} 
square = function(x) { 
  return x * x; 
}; 
list = [1, 2, 3, 4, 5];
http://coffeescript.org/
CoffeeScript syntax
# Splats: 
race = (winner, runners...) ­> 
  print winner, runners
var race, 
  slice = [].slice; 
race = function() { 
  var runners, winner; 
  winner = arguments[0], 
    runners = 2 <= arguments.length ?
      slice.call(arguments, 1) : [];
  return print(winner, runners); 
};
http://coffeescript.org/
CoffeeScript usecase
class DataWidgetCtrl 
  fetchData: ­> 
    @$timeout =>
      @table.loaded = true 
      resourceObject = angular.fromJson(@$attrs.resource) 
      model = @$injector.get(resourceObject.model) 
      @table.promise = model[resourceObject.method](resourceObject.id).then (res) =>
        @setData(res) 
        @init() 
      , (res) =>
        @getHeader(@def.i18n, @table) 
        @table.error = res.status 
    , 0 
...
var DataWidgetCtrl; 
DataWidgetCtrl = (function() { 
  DataWidgetCtrl.prototype.fetchData = function() { 
    return this.$timeout((function(_this) { 
      return function() { 
        var model, resourceObject; 
        _this.table.loaded = true; 
        resourceObject = angular.fromJson(_this.$attrs.resource); 
        model = _this.$injector.get(resourceObject.model); 
        return _this.table.promise = model[resourceObject.method] 
         (resourceObject.id).then(function(res) { 
          _this.setData(res); 
          return _this.init(); 
        }, function(res) { 
          _this.getHeader(_this.def.i18n, _this.table); 
          return _this.table.error = res.status; 
        }); 
      }; 
    })(this), 0); 
  }; 
... 
  return DataWidgetCtrl; 
})();
writing JavaScript is
not trendy anymore ;)

4Developers: Tomasz Ducin- JavaScript + Java = TypeScript