TypeScript - Silver Bullet for the Full-stack Developers

Rutenis Turcinas
Rutenis TurcinasJava Software Engineer at Intermedix
TypeScript
Write JavaScript the way you really want to
Rūtenis Turčinas - rutenis.turcinas@gmail.com
Author
 Rūtenis Turčinas
 rutenis.turcinas@gmail.com
 https://github.com/rootis/jug-topic-1.git
http://www.typescriptlang.org/Content/TypeScript Language Specification.pdf
Agenda
Specification Integration
BuildClean Code
Questions Thoughts Suggestions
TypeScript. What is it? Do we need it?
 TypeScript is a typed superset of JavaScript that compiles to plain JavaScript
 Made by Microsoft
 Open Source
 Google had plans to release AtScript language, but desided to use TypeScript
 Google and Microsoft are writing the Angular 2 framework in TypeScript
 If your project uses JavaScript – TypeScript would be better
Difference between other languages
 CoffeeScript
 More differences from JavaScript
 You can not use plain JavaScript in *.coffee files
 Dart
 Has an own virtual machine
 Browser manufacturers has no plans to support Dart in the near future
How TypeScript works?
 TypeScript file: test.ts
 > tsc test.ts
 Compiler makes test.js file
 JavaScript file will be executed by browser
 > tsc test.ts –sourcemap
 Compiler makes the same test.js and one more file: test.js.map
 Map file used to map *.js with *.ts file lines (to debug *.ts file instead of *.js)
Hello World!
Data types
 boolean
 number
 string
 Array
 enum
 any (try to avoid it)
 void
Statements, loops, functions
 Simple variable assignment
 var variableName: dataType = value;
 Variable which data type is a function
 var variableName: (paramName: dataType) => returnType = value;
 Complex data type (do not use such data types)
 var person: {name: string; surname: string; age: number,
isMale: () => boolean} = null;
Classes, interfaces, methods
interface UsersGroup {
getLanguage: () => string;
}
class Jug implements UsersGroup {
public getLanguage(): string {
return "Java " + this.getJavaVersionTitle();
}
protected getJavaVersion(): number {
return 1.7;
}
private getJavaVersionTitle(): string {
return "v" + this.getJavaVersion();
}
}
Inheritance, overriding
class KaunasJug extends Jug {
protected getJavaVersion(): number {
return 1.8;
}
}
function printUsersGroupLanguage(usersGroup: UsersGroup): void {
console.log(usersGroup.getLanguage());
}
printUsersGroupLanguage(new Jug());
printUsersGroupLanguage(new KaunasJug());
Overloading
interface UsersGroup {
getLanguage(isUpperCase: boolean): string;
getLanguage(versionPrefix: string): string;
}
class KaunasJug implements UsersGroup {
getLanguage(property?: any): string {
if (typeof property === 'boolean'){
return property ? "JAVA v1.8" : "Java v1.8";
} else if (typeof property === "string") {
return "Java " + property + "1.8";
}
}
}
Generics
function printProperty<T>(property: T): void {
console.log(property);
}
interface UserGroupArray<T extends Language> {
add(... languages: T[]): void;
printAllGroups(): void;
}
Lambdas (use as little as possible)
class JavaUsersGroup {
private city: string;
constructor(city: string) {
this.city = city;
}
public printTitle1(): void {
console.log(this.city + " JUG");
}
public printTitle2 = (): void => {
console.log(this.city + " JUG");
};
}
Modules
module usersGroup {
export class API {
public static init(data: any) {
new ViewModel(data.someJSON);
}
}
class ViewModel {
constructor(jsonDataToLoad: string) {
console.log('Loading...');
}
}
class SomeInnerClass {
}
}
External libraries
 Large API, difficult to use, hard to remember: actions, events, properties, sub
modules...
 For example: using selector you get jQuery object. You want to get it‘s specific
child. Which method to use? Can you use the selector?
 99% of developers would use google. More convenient to use ctrl+space and get
the suggestion:
 And if you try to do something ridiculous – the code won‘t compile:
DefinetlyTyped - *.d.ts
 Declaration file (*.d.ts) describes the library or module
 > tsc --declaration file.ts
declare module usersGroup {
class API {
static init(data: any): void;
}
}
Definition manager - tsd
 LOTS of the *.d.ts files are here: https://github.com/borisyankov/DefinitelyTyped
 But its hard to search and download... Is there a better way?
 > npm install tsd –g
 E.g. you want to use library lodash
 Does it has lodash.d.ts file? Which version?
 > tsd query lodash
 Yes! It exists. We want to download lodash.d.ts file
 > tsd install lodash –save
 Using -save you wil store the information about installed *.d.ts in tsd.json
Libraries without *.d.ts or legacy code
 We are using super secret library...
 In our project exists lots of legacy code...
 But we still want to use TypeScript!
 What to do?
 Need to create declaration file for that library or legacy code (*.d.ts)
interface A_Static {
new(m: any): A_Instance;
st: string;
}
interface A_Instance {
inst: number;
}
declare var A: A_Static;
Dependency management tools
 Internal modules
 External modules: import $ = require('jquery');
 commonJS
 --module commonjs
 AMD - requireJS
 --module amd
How to write TypeScript correctly?
 TypeScript also can be terrible... if its plain JavaScript
 How to prevent it?
 Use simple rules:
 Every variable, property, or function result – must have defined data type
 Never use any data type
 Use same clean code conventions like in server side
Decouple modules
 Most of the times JavaScript logic lives in one place
 Large files tightly coupled in different ways
 Impossible to do refactoring without bugs
 How to solve it?
 Decouple logic to different modules
 Don‘t copy paste, just depend on some module
 Define strict public API for integration with other modules
Single responsibility for every item
 One module/class/method should be responsible just for one thing
 Currently we are trying one approach:
 If length of file is more than 200 lines – we should rethink: is it only
responsible for one thing?
 If length of method is more than 5 lines – we should rethink: is it only
responsible for one thing?
 In our project:
 97% of files have <= 200 lines
 72% of methods have <= 5 lines (in 4 files: ~200, ~180, ~150, ~120)
Hide as much as possible
 Encapsulate code
 Export only public API
 One file - one module
 Except – model entities
 Much easier to refactor hidden code
Try to keep code in first level
 JAVA developers can feel much more convenient by having source code in first
level
 Less complexity
 Easyer to understand and support
OK. But my friend uses SunOS and VIM
for editing source code. Can he..?
 Sure thing!
One more thing… Production needs one
file rather than 3
 For development we want all files: *.ts, *.js, *.js.map
 But for production we want only one: compressed *.js
 You can configure build scripts
 E.g. maven resource filtering
Large project. Lots of code.
How to test it?
 Karma, Jasmine, Mocha, tsJunit, Qjunit, ...
 Karma tests can be binded or decoupled from back end unit tests
 Binded tests can be skipped together with java tests using –DskipTests
 Decoupled tests can be skipped separate from java tests using custom
properties
Minuses in TypeScript
 Eclipse IDE
 After compiler version update your code may be broken...
Questions Thoughts Suggestions
1 of 32

Recommended

Typescript for the programmers who like javascript by
Typescript for the programmers who like javascriptTypescript for the programmers who like javascript
Typescript for the programmers who like javascriptAndrei Sebastian Cîmpean
1.5K views64 slides
TypeScript Best Practices by
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practicesfelixbillon
3K views57 slides
TypeScript - An Introduction by
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An IntroductionNexThoughts Technologies
5.2K views52 slides
Typescript by
TypescriptTypescript
TypescriptNikhil Thomas
530 views26 slides
Getting started with typescript and angular 2 by
Getting started with typescript  and angular 2Getting started with typescript  and angular 2
Getting started with typescript and angular 2Knoldus Inc.
4.4K views29 slides

More Related Content

What's hot

002. Introducere in type script by
002. Introducere in type script002. Introducere in type script
002. Introducere in type scriptDmitrii Stoian
639 views56 slides
TypeScript: coding JavaScript without the pain by
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painSander Mak (@Sander_Mak)
17K views61 slides
TypeScript Overview by
TypeScript OverviewTypeScript Overview
TypeScript OverviewAniruddha Chakrabarti
5.9K views52 slides
TypeScript intro by
TypeScript introTypeScript intro
TypeScript introAts Uiboupin
1.6K views36 slides
Learning typescript by
Learning typescriptLearning typescript
Learning typescriptAlexandre Marreiros
3.5K views37 slides
Type script - advanced usage and practices by
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practicesIwan van der Kleijn
855 views25 slides

What's hot(20)

002. Introducere in type script by Dmitrii Stoian
002. Introducere in type script002. Introducere in type script
002. Introducere in type script
Dmitrii Stoian639 views
Introducing type script by Remo Jansen
Introducing type scriptIntroducing type script
Introducing type script
Remo Jansen2.4K views
Power Leveling your TypeScript by Offirmo
Power Leveling your TypeScriptPower Leveling your TypeScript
Power Leveling your TypeScript
Offirmo712 views
Typescript ppt by akhilsreyas
Typescript pptTypescript ppt
Typescript ppt
akhilsreyas13.7K views
TypeScript: Angular's Secret Weapon by Laurent Duveau
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
Laurent Duveau1.1K views
Typescript in 30mins by Udaya Kumar
Typescript in 30mins Typescript in 30mins
Typescript in 30mins
Udaya Kumar875 views
Getting Started with TypeScript by Gil Fink
Getting Started with TypeScriptGetting Started with TypeScript
Getting Started with TypeScript
Gil Fink708 views
TypeScript: Basic Features and Compilation Guide by Nascenia IT
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation Guide
Nascenia IT398 views
TypeScript introduction to scalable javascript application by Andrea Paciolla
TypeScript introduction to scalable javascript applicationTypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript application
Andrea Paciolla403 views

Viewers also liked

«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21 by
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21MoscowJS
1.5K views18 slides
Typescript + Graphql = <3 by
Typescript + Graphql = <3Typescript + Graphql = <3
Typescript + Graphql = <3felixbillon
666 views18 slides
TypeScript by
TypeScriptTypeScript
TypeScriptGetDev.NET
1.6K views26 slides
TypeScript Seminar by
TypeScript SeminarTypeScript Seminar
TypeScript SeminarHaim Michael
4.4K views219 slides
TypeScript: особенности разработки / Александр Майоров (Tutu.ru) by
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)Ontico
1.9K views61 slides
TypeScript: Un lenguaje aburrido para programadores torpes y tristes by
TypeScript: Un lenguaje aburrido para programadores torpes y tristesTypeScript: Un lenguaje aburrido para programadores torpes y tristes
TypeScript: Un lenguaje aburrido para programadores torpes y tristesMicael Gallego
6.1K views138 slides

Viewers also liked(13)

«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21 by MoscowJS
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
MoscowJS1.5K views
Typescript + Graphql = <3 by felixbillon
Typescript + Graphql = <3Typescript + Graphql = <3
Typescript + Graphql = <3
felixbillon666 views
TypeScript by GetDev.NET
TypeScriptTypeScript
TypeScript
GetDev.NET1.6K views
TypeScript Seminar by Haim Michael
TypeScript SeminarTypeScript Seminar
TypeScript Seminar
Haim Michael4.4K views
TypeScript: особенности разработки / Александр Майоров (Tutu.ru) by Ontico
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
Ontico1.9K views
TypeScript: Un lenguaje aburrido para programadores torpes y tristes by Micael Gallego
TypeScript: Un lenguaje aburrido para programadores torpes y tristesTypeScript: Un lenguaje aburrido para programadores torpes y tristes
TypeScript: Un lenguaje aburrido para programadores torpes y tristes
Micael Gallego6.1K views
Typescript tips & tricks by Ori Calvo
Typescript tips & tricksTypescript tips & tricks
Typescript tips & tricks
Ori Calvo1K views
Александр Русаков - TypeScript 2 in action by MoscowJS
Александр Русаков - TypeScript 2 in actionАлександр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in action
MoscowJS881 views
TypeScript for Java Developers by Yakov Fain
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
Yakov Fain3.9K views
TypeScript Introduction by Dmitry Sheiko
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko7.4K views
Why TypeScript? by FITC
Why TypeScript?Why TypeScript?
Why TypeScript?
FITC3.9K views

Similar to TypeScript - Silver Bullet for the Full-stack Developers

MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift by
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using SwiftDiego Freniche Brito
104 views35 slides
Introduction to Software Development by
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software DevelopmentZeeshan MIrza
8.6K views34 slides
Android develop guideline by
Android develop guidelineAndroid develop guideline
Android develop guidelineKan-Han (John) Lu
195 views13 slides
An Introduction to TypeScript by
An Introduction to TypeScriptAn Introduction to TypeScript
An Introduction to TypeScriptWrapPixel
53 views7 slides
Parse cloud code by
Parse cloud codeParse cloud code
Parse cloud code維佋 唐
13.6K views72 slides
Workflow story: Theory versus practice in Large Enterprises by
Workflow story: Theory versus practice in Large EnterprisesWorkflow story: Theory versus practice in Large Enterprises
Workflow story: Theory versus practice in Large EnterprisesPuppet
3.1K views44 slides

Similar to TypeScript - Silver Bullet for the Full-stack Developers(20)

MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift by Diego Freniche Brito
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
Introduction to Software Development by Zeeshan MIrza
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
Zeeshan MIrza8.6K views
An Introduction to TypeScript by WrapPixel
An Introduction to TypeScriptAn Introduction to TypeScript
An Introduction to TypeScript
WrapPixel53 views
Parse cloud code by 維佋 唐
Parse cloud codeParse cloud code
Parse cloud code
維佋 唐13.6K views
Workflow story: Theory versus practice in Large Enterprises by Puppet
Workflow story: Theory versus practice in Large EnterprisesWorkflow story: Theory versus practice in Large Enterprises
Workflow story: Theory versus practice in Large Enterprises
Puppet3.1K views
Workflow story: Theory versus Practice in large enterprises by Marcin Piebiak by NETWAYS
Workflow story: Theory versus Practice in large enterprises by Marcin PiebiakWorkflow story: Theory versus Practice in large enterprises by Marcin Piebiak
Workflow story: Theory versus Practice in large enterprises by Marcin Piebiak
NETWAYS504 views
I Just Want to Run My Code: Waypoint, Nomad, and Other Things by Michael Lange
I Just Want to Run My Code: Waypoint, Nomad, and Other ThingsI Just Want to Run My Code: Waypoint, Nomad, and Other Things
I Just Want to Run My Code: Waypoint, Nomad, and Other Things
Michael Lange35 views
"Xapi-lang For declarative code generation" By James Nelson by GWTcon
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson
GWTcon 833 views
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge by Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume LaforgeGroovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Guillaume Laforge1.1K views
Building Server Applications Using ObjectiveC And GNUstep by guest9efd1a1
Building Server Applications Using ObjectiveC And GNUstepBuilding Server Applications Using ObjectiveC And GNUstep
Building Server Applications Using ObjectiveC And GNUstep
guest9efd1a14.3K views
Building Server Applications Using Objective C And Gn Ustep by wangii
Building Server Applications Using Objective C And Gn UstepBuilding Server Applications Using Objective C And Gn Ustep
Building Server Applications Using Objective C And Gn Ustep
wangii537 views
JavaScript Miller Columns by Jonathan Fine
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
Jonathan Fine1.4K views

Recently uploaded

DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema by
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - GeertsemaDSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - GeertsemaDeltares
12 views13 slides
Les nouveautés produit Neo4j by
 Les nouveautés produit Neo4j Les nouveautés produit Neo4j
Les nouveautés produit Neo4jNeo4j
27 views46 slides
Neo4j y GenAI by
Neo4j y GenAI Neo4j y GenAI
Neo4j y GenAI Neo4j
35 views41 slides
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -... by
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...Deltares
6 views15 slides
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J... by
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...Deltares
7 views24 slides
Tridens DevOps by
Tridens DevOpsTridens DevOps
Tridens DevOpsTridens
9 views28 slides

Recently uploaded(20)

DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema by Deltares
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - GeertsemaDSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
Deltares12 views
Les nouveautés produit Neo4j by Neo4j
 Les nouveautés produit Neo4j Les nouveautés produit Neo4j
Les nouveautés produit Neo4j
Neo4j27 views
Neo4j y GenAI by Neo4j
Neo4j y GenAI Neo4j y GenAI
Neo4j y GenAI
Neo4j35 views
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -... by Deltares
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...
Deltares6 views
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J... by Deltares
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...
Deltares7 views
Tridens DevOps by Tridens
Tridens DevOpsTridens DevOps
Tridens DevOps
Tridens9 views
Elevate your SAP landscape's efficiency and performance with HCL Workload Aut... by HCLSoftware
Elevate your SAP landscape's efficiency and performance with HCL Workload Aut...Elevate your SAP landscape's efficiency and performance with HCL Workload Aut...
Elevate your SAP landscape's efficiency and performance with HCL Workload Aut...
HCLSoftware6 views
DSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - Afternoon by Deltares
DSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - AfternoonDSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - Afternoon
DSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - Afternoon
Deltares11 views
Cycleops - Automate deployments on top of bare metal.pptx by Thanassis Parathyras
Cycleops - Automate deployments on top of bare metal.pptxCycleops - Automate deployments on top of bare metal.pptx
Cycleops - Automate deployments on top of bare metal.pptx
DSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - Parker by Deltares
DSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - ParkerDSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - Parker
DSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - Parker
Deltares8 views
How to Install and Activate Email-Researcher by eGrabber
How to Install and Activate Email-ResearcherHow to Install and Activate Email-Researcher
How to Install and Activate Email-Researcher
eGrabber19 views
DSD-INT 2023 Delft3D FM Suite 2024.01 2D3D - New features + Improvements - Ge... by Deltares
DSD-INT 2023 Delft3D FM Suite 2024.01 2D3D - New features + Improvements - Ge...DSD-INT 2023 Delft3D FM Suite 2024.01 2D3D - New features + Improvements - Ge...
DSD-INT 2023 Delft3D FM Suite 2024.01 2D3D - New features + Improvements - Ge...
Deltares16 views
How to Make the Most of Regression and Unit Testing.pdf by Abhay Kumar
How to Make the Most of Regression and Unit Testing.pdfHow to Make the Most of Regression and Unit Testing.pdf
How to Make the Most of Regression and Unit Testing.pdf
Abhay Kumar10 views
SUGCON ANZ Presentation V2.1 Final.pptx by Jack Spektor
SUGCON ANZ Presentation V2.1 Final.pptxSUGCON ANZ Presentation V2.1 Final.pptx
SUGCON ANZ Presentation V2.1 Final.pptx
Jack Spektor21 views
Software evolution understanding: Automatic extraction of software identifier... by Ra'Fat Al-Msie'deen
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...
El Arte de lo Possible by Neo4j
El Arte de lo PossibleEl Arte de lo Possible
El Arte de lo Possible
Neo4j34 views
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t... by Deltares
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...
Deltares9 views
What Can Employee Monitoring Software Do?​ by wAnywhere
What Can Employee Monitoring Software Do?​What Can Employee Monitoring Software Do?​
What Can Employee Monitoring Software Do?​
wAnywhere18 views

TypeScript - Silver Bullet for the Full-stack Developers

  • 1. TypeScript Write JavaScript the way you really want to Rūtenis Turčinas - rutenis.turcinas@gmail.com
  • 2. Author  Rūtenis Turčinas  rutenis.turcinas@gmail.com  https://github.com/rootis/jug-topic-1.git
  • 6. TypeScript. What is it? Do we need it?  TypeScript is a typed superset of JavaScript that compiles to plain JavaScript  Made by Microsoft  Open Source  Google had plans to release AtScript language, but desided to use TypeScript  Google and Microsoft are writing the Angular 2 framework in TypeScript  If your project uses JavaScript – TypeScript would be better
  • 7. Difference between other languages  CoffeeScript  More differences from JavaScript  You can not use plain JavaScript in *.coffee files  Dart  Has an own virtual machine  Browser manufacturers has no plans to support Dart in the near future
  • 8. How TypeScript works?  TypeScript file: test.ts  > tsc test.ts  Compiler makes test.js file  JavaScript file will be executed by browser  > tsc test.ts –sourcemap  Compiler makes the same test.js and one more file: test.js.map  Map file used to map *.js with *.ts file lines (to debug *.ts file instead of *.js)
  • 10. Data types  boolean  number  string  Array  enum  any (try to avoid it)  void
  • 11. Statements, loops, functions  Simple variable assignment  var variableName: dataType = value;  Variable which data type is a function  var variableName: (paramName: dataType) => returnType = value;  Complex data type (do not use such data types)  var person: {name: string; surname: string; age: number, isMale: () => boolean} = null;
  • 12. Classes, interfaces, methods interface UsersGroup { getLanguage: () => string; } class Jug implements UsersGroup { public getLanguage(): string { return "Java " + this.getJavaVersionTitle(); } protected getJavaVersion(): number { return 1.7; } private getJavaVersionTitle(): string { return "v" + this.getJavaVersion(); } }
  • 13. Inheritance, overriding class KaunasJug extends Jug { protected getJavaVersion(): number { return 1.8; } } function printUsersGroupLanguage(usersGroup: UsersGroup): void { console.log(usersGroup.getLanguage()); } printUsersGroupLanguage(new Jug()); printUsersGroupLanguage(new KaunasJug());
  • 14. Overloading interface UsersGroup { getLanguage(isUpperCase: boolean): string; getLanguage(versionPrefix: string): string; } class KaunasJug implements UsersGroup { getLanguage(property?: any): string { if (typeof property === 'boolean'){ return property ? "JAVA v1.8" : "Java v1.8"; } else if (typeof property === "string") { return "Java " + property + "1.8"; } } }
  • 15. Generics function printProperty<T>(property: T): void { console.log(property); } interface UserGroupArray<T extends Language> { add(... languages: T[]): void; printAllGroups(): void; }
  • 16. Lambdas (use as little as possible) class JavaUsersGroup { private city: string; constructor(city: string) { this.city = city; } public printTitle1(): void { console.log(this.city + " JUG"); } public printTitle2 = (): void => { console.log(this.city + " JUG"); }; }
  • 17. Modules module usersGroup { export class API { public static init(data: any) { new ViewModel(data.someJSON); } } class ViewModel { constructor(jsonDataToLoad: string) { console.log('Loading...'); } } class SomeInnerClass { } }
  • 18. External libraries  Large API, difficult to use, hard to remember: actions, events, properties, sub modules...  For example: using selector you get jQuery object. You want to get it‘s specific child. Which method to use? Can you use the selector?  99% of developers would use google. More convenient to use ctrl+space and get the suggestion:  And if you try to do something ridiculous – the code won‘t compile:
  • 19. DefinetlyTyped - *.d.ts  Declaration file (*.d.ts) describes the library or module  > tsc --declaration file.ts declare module usersGroup { class API { static init(data: any): void; } }
  • 20. Definition manager - tsd  LOTS of the *.d.ts files are here: https://github.com/borisyankov/DefinitelyTyped  But its hard to search and download... Is there a better way?  > npm install tsd –g  E.g. you want to use library lodash  Does it has lodash.d.ts file? Which version?  > tsd query lodash  Yes! It exists. We want to download lodash.d.ts file  > tsd install lodash –save  Using -save you wil store the information about installed *.d.ts in tsd.json
  • 21. Libraries without *.d.ts or legacy code  We are using super secret library...  In our project exists lots of legacy code...  But we still want to use TypeScript!  What to do?  Need to create declaration file for that library or legacy code (*.d.ts) interface A_Static { new(m: any): A_Instance; st: string; } interface A_Instance { inst: number; } declare var A: A_Static;
  • 22. Dependency management tools  Internal modules  External modules: import $ = require('jquery');  commonJS  --module commonjs  AMD - requireJS  --module amd
  • 23. How to write TypeScript correctly?  TypeScript also can be terrible... if its plain JavaScript  How to prevent it?  Use simple rules:  Every variable, property, or function result – must have defined data type  Never use any data type  Use same clean code conventions like in server side
  • 24. Decouple modules  Most of the times JavaScript logic lives in one place  Large files tightly coupled in different ways  Impossible to do refactoring without bugs  How to solve it?  Decouple logic to different modules  Don‘t copy paste, just depend on some module  Define strict public API for integration with other modules
  • 25. Single responsibility for every item  One module/class/method should be responsible just for one thing  Currently we are trying one approach:  If length of file is more than 200 lines – we should rethink: is it only responsible for one thing?  If length of method is more than 5 lines – we should rethink: is it only responsible for one thing?  In our project:  97% of files have <= 200 lines  72% of methods have <= 5 lines (in 4 files: ~200, ~180, ~150, ~120)
  • 26. Hide as much as possible  Encapsulate code  Export only public API  One file - one module  Except – model entities  Much easier to refactor hidden code
  • 27. Try to keep code in first level  JAVA developers can feel much more convenient by having source code in first level  Less complexity  Easyer to understand and support
  • 28. OK. But my friend uses SunOS and VIM for editing source code. Can he..?  Sure thing!
  • 29. One more thing… Production needs one file rather than 3  For development we want all files: *.ts, *.js, *.js.map  But for production we want only one: compressed *.js  You can configure build scripts  E.g. maven resource filtering
  • 30. Large project. Lots of code. How to test it?  Karma, Jasmine, Mocha, tsJunit, Qjunit, ...  Karma tests can be binded or decoupled from back end unit tests  Binded tests can be skipped together with java tests using –DskipTests  Decoupled tests can be skipped separate from java tests using custom properties
  • 31. Minuses in TypeScript  Eclipse IDE  After compiler version update your code may be broken...