SlideShare a Scribd company logo
1 of 38
Microsoft Typescript
BY AMINE EL HARRAK
SOFTWARE ENGINEER (FULL-STACK DEVELOPER) @sqli
2017
Agenda
 Introduction
 Installation & Who to use TS ?
 Features
 Do's and Don'ts
 Conclusion
Introduction JAVASCRIPT THAT SCALES.
Introduction
 Introduction
 How use TS ?
 ***!?
 Woe
 Facts
 Ecosystem
Introduction
 Microsoft Typescript is a statically
typed compiled language to clean
and a simple plain old JavaScript code
which runs on any browser, in Node.js
or in any JavaScript engine that
supports ECMAScript 3 (or newer).
Recent rise of TypeScript’s popularity,
data from Google Trends.
Is Anyone using Typescript ?
 Angularjs2
 IONIC 2
 DOJO
 …
***!?
Why would I want to rewrite all of the applications I already have
(Next apps) in this new language?
The simple answer is you don’t have to.
Weight of Evidence
 Code is hard to navigate
 Autocompletion
 Refactorings
 Compiler checks
 debug
 …
TypeScript Facts
 Large and scale application development
 Language, not a framework
 Cross-compiles to JavaScript
 Produces idiomatic JavaScript
 Doesn‘t try to replace JavaScript
 Offers missing language features (Anticipates ES6, …)
 Is a superset of JavaScript (Promises easy migration of JS code)
 JS libs can be used easily
 (Optional) static typing
 …
How to get setup
?
INSTALLING TYPESCRIPT
How to get setup ?
 Installing TypeScript
 Text Editors Support
 Compiling to JavaScript
Installing TypeScript
There are two main ways to get the TypeScript tools:
 Via npm (the Node.js package manager) / yarn add typescript
 By installing TypeScript’s Visual Studio plugins.
Installing TypeScript
The easiest way to setup TypeScript is via npm.
Using the command below we can install the TypeScript package globally, making the TS
compiler available in all of our projects :
 yarn add typescript or npm install -g typescript //For the latest stable version
 npm install -g typescript@next //For our nightly builds
Try opening a terminal anywhere and running tsc -v to see if it has been properly installed.
$ tsc -v
version 2.2.1
Text Editors With TypeScript Support
TypeScript is an open-source project but is developed and maintained by Microsoft and as such was
originally supported only in Microsoft’s Visual Studio platform. Nowadays, there are a lot more text editors
and IDEs that either natively or through plugins offer support for the TypeScript syntax, auto-complete
suggestions, error catching, and even built-in compilers.
 Visual Studio Code – Microsoft’s other, lightweight open-source code editor. TypeScript support is built
in.
 Official Free Plugin for Sublime Text.
 The latest version of WebStorm comes with built in support.
 More including Vim, Atom, Emacs and others.
Compiling to JavaScript
TypeScript is written in .ts files (or .tsx for JSX), which can’t be used directly in the browser and
need to be translated to vanilla .js first. This compilation process can be done in a number of
different ways:
 In the terminal using the previously mentioned command line tool tsc.
 Directly in Visual Studio or some of the other IDEs and text editors.
 Using automated task runners such as grunt, gulp.
Compiling to JavaScript
The following command takes a TypeScript file named main.ts and translates it into its JavaScript
version main.js. If main.js already exists it will be overwritten.
tsc main.ts
We can also compile multiple files at once by listing all of them or by applying wildcards :
# Will result in separate .js files: main.js worker.js.
tsc main.ts worker.ts
# Compiles all .ts files in the current folder. Does NOT work recursively. tsc *.ts
Compiling to JavaScript
We can also use the --watch option to automatically compile a TypeScript file when changes are
made:
# Initializes a watcher process that will keep main.js up to date.
tsc main.ts --watch
More advanced TypeScript users can also create a tsconfig.json file, consisting of various build
settings. A configuration file is very handy when working on large projects with lots of .ts files
since it somewhat automates the process. You can read more about tsconfig.json in the
TypeScript docs.
Features of
TypeScript
Language Features
 Type annotations
 Type inference
 Compile time type checking
 Optional, default and rest parameters
 Classes
 Interfaces
 Structural typing
 Arrow function expressions
 Enums
 Generics
 Modules
 Tuple types
 Union types and type guards
TypeScript grammar
Class
class Person {
protected name: string;
constructor(name: string) { this.name = name; }
}
class Employee extends Person {
private department: string;
constructor(name: string, department: string) {
super(name);
this.department = department;
}
public getElevatorPitch() {
return `Hello, my name is ${this.name} and I
work in ${this.department}.`;
}
}
let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // error
Interfaces
interface ClockInterface {
currentTime: Date;
setTime(d: Date);
}
class Clock implements ClockInterface {
currentTime: Date;
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) { }
}
Generics
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("myString"); // type of output will be 'string'
Enums
const enum Directions {
Up,
Down,
Left,
Right
}
let directions = [Directions.Up, Directions.Down, Directions.Left,
Directions.Right]
Examples
Modules
//Validation.ts
export interface StringValidator {
isAcceptable(s: string): boolean;
}
//ZipCodeValidator.ts
export const numberRegexp = /^[0-9]+$/;
export class ZipCodeValidator implements
StringValidator {
isAcceptable(s: string) {
return s.length === 5 &&
numberRegexp.test(s);
}
}
Do's and Don'ts
Do's and Don'ts |General Types
Don’t ever use the types Number, String, Boolean, or Object. These types refer to non-primitive boxed
objects that are almost never used appropriately in JavaScript code.
/* WRONG */
function reverse(s: String): String;
/* OK */
function reverse(s: string): string;
If you’re tempted to use the type Object, consider using any instead. There is currently no way in TypeScript
to specify an object that is “not a primitive”.
Do's and Don'ts |Callback Types
Don’t use the return type any for callbacks whose value will be ignored:
/* WRONG */
function fn(x: () => any) {
x();
}
/* OK */
function fn(x: () => void) {
x();
}
Do's and Don'ts |Callback Types
Example :
function fn(x: () => void) {
var k = x(); // oops! meant to do something else
k.doSomething(); // error, but would be OK if the return type had been 'any‘
}
Why: Using void is safer because it prevents you from accidently using the return value of x in an
unchecked way
Do's and Don'ts |Overloads and Callbacks
Don’t write separate overloads that differ only on callback arity -> Do write a single overload using the
maximum arity:
/* WRONG */
declare function beforeAll(action: () => void, timeout?: number): void;
declare function beforeAll(action: (done: DoneFn) => void, timeout?: number): void;
/* OK */
declare function beforeAll(action: (done: DoneFn) => void, timeout?: number): void;
Do's and Don'ts |Function Overloads
Don’t put more general overloads before more specific overloads, Do sort overloads by putting the more
general signatures after more specific signatures:
/* WRONG */
declare function fn(x: any): any;
declare function fn(x: HTMLElement): number;
declare function fn(x: HTMLDivElement): string;
var myElem: HTMLDivElement;
var x = fn(myElem); // x: any, wat?
/* OK */
declare function fn(x: HTMLDivElement): string;
declare function fn(x: HTMLElement): number;
declare function fn(x: any): any;
var myElem: HTMLDivElement;
var x = fn(myElem); // x: string,
Why: TypeScript chooses the first matching overload when resolving function calls. When an earlier
overload is “more general” than a later one, the later one is effectively hidden and cannot be called.
Do's and Don'ts |Use Optional Parameters
Don’t write several overloads that differ only in trailing parameters, Do use optional parameters whenever
possible:
/* WRONG */
interface Example {
diff(one: string): number;
diff(one: string, two: string): number;
diff(one: string, two: string, three: boolean): number;
}
/* OK */
interface Example {
diff(one: string, two?: string, three?: boolean): number;
}
Why: TypeScript chooses the first matching overload when resolving function calls. When an earlier
overload is “more general” than a later one, the later one is effectively hidden and cannot be called.
Do's and Don'ts |Use Union Types
Don’t write overloads that differ by type in only one argument position, Do use union types whenever
possible:
/* WRONG */
interface Moment {
utcOffset(): number;
utcOffset(b: number): Moment;
utcOffset(b: string): Moment;
}
/* OK */
interface Moment {
utcOffset(): number;
utcOffset(b: number|string): Moment;
}
Note that we didn’t make b optional here because the return types of the signatures differ.
Migrating from
JavaScript
Step
projectRoot
├── src
│ ├── file1.js
│ └── file2.js
├── built
└── tsconfig.json
1. Setting up your Directories
2. Writing a Configuration File
3. Integrating with Build Tools (Gulp, Webpack …)
{
"compilerOptions": {
"outDir": "./built",
"allowJs": true,
"target": "es5"
},
"include": [
"./src/**/*"
]
}
“
”
Thank you !

More Related Content

What's hot

TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painSander Mak (@Sander_Mak)
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practicesIwan van der Kleijn
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideNascenia IT
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
Une introduction à Javascript et ECMAScript 6
Une introduction à Javascript et ECMAScript 6Une introduction à Javascript et ECMAScript 6
Une introduction à Javascript et ECMAScript 6Jean-Baptiste Vigneron
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxMalla Reddy University
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBhargav Anadkat
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScriptT11 Sessions
 
What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?Simplilearn
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentationritika1
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentationAdhoura Academy
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - IntroductionWebStackAcademy
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolvedtrxcllnt
 
002. Introducere in type script
002. Introducere in type script002. Introducere in type script
002. Introducere in type scriptDmitrii Stoian
 

What's hot (20)

TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
 
TypeScript Presentation
TypeScript PresentationTypeScript Presentation
TypeScript Presentation
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practices
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation Guide
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 
TypeScript intro
TypeScript introTypeScript intro
TypeScript intro
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
TypeScript
TypeScriptTypeScript
TypeScript
 
Une introduction à Javascript et ECMAScript 6
Une introduction à Javascript et ECMAScript 6Une introduction à Javascript et ECMAScript 6
Une introduction à Javascript et ECMAScript 6
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
 
TypeScript VS JavaScript.pptx
TypeScript VS JavaScript.pptxTypeScript VS JavaScript.pptx
TypeScript VS JavaScript.pptx
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolved
 
002. Introducere in type script
002. Introducere in type script002. Introducere in type script
002. Introducere in type script
 

Viewers also liked

Power Leveling your TypeScript
Power Leveling your TypeScriptPower Leveling your TypeScript
Power Leveling your TypeScriptOffirmo
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponLaurent Duveau
 
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21MoscowJS
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersRutenis Turcinas
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
Александр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in actionАлександр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in actionMoscowJS
 
Typescript tips & tricks
Typescript tips & tricksTypescript tips & tricks
Typescript tips & tricksOri Calvo
 
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)Ontico
 
TypeScript: Un lenguaje aburrido para programadores torpes y tristes
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
 
Angular 2 - Typescript
Angular 2  - TypescriptAngular 2  - Typescript
Angular 2 - TypescriptNathan Krasney
 
Typescript + Graphql = <3
Typescript + Graphql = <3Typescript + Graphql = <3
Typescript + Graphql = <3felixbillon
 
TypeScript Seminar
TypeScript SeminarTypeScript Seminar
TypeScript SeminarHaim Michael
 

Viewers also liked (15)

Power Leveling your TypeScript
Power Leveling your TypeScriptPower Leveling your TypeScript
Power Leveling your TypeScript
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
 
Typescript
TypescriptTypescript
Typescript
 
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack Developers
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Александр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in actionАлександр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in action
 
Typescript tips & tricks
Typescript tips & tricksTypescript tips & tricks
Typescript tips & tricks
 
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
 
TypeScript: Un lenguaje aburrido para programadores torpes y tristes
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
 
TypeScript
TypeScriptTypeScript
TypeScript
 
Angular 2 - Typescript
Angular 2  - TypescriptAngular 2  - Typescript
Angular 2 - Typescript
 
Typescript + Graphql = <3
Typescript + Graphql = <3Typescript + Graphql = <3
Typescript + Graphql = <3
 
TypeScript Seminar
TypeScript SeminarTypeScript Seminar
TypeScript Seminar
 
TypeScriptで快適javascript
TypeScriptで快適javascriptTypeScriptで快適javascript
TypeScriptで快適javascript
 

Similar to Getting started with typescript

Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java scriptmichaelaaron25322
 
Introduction to TypeScript by Winston Levi
Introduction to TypeScript by Winston LeviIntroduction to TypeScript by Winston Levi
Introduction to TypeScript by Winston LeviWinston Levi
 
Getting started with typescript and angular 2
Getting started with typescript  and angular 2Getting started with typescript  and angular 2
Getting started with typescript and angular 2Knoldus Inc.
 
Typescript for the programmers who like javascript
Typescript for the programmers who like javascriptTypescript for the programmers who like javascript
Typescript for the programmers who like javascriptAndrei Sebastian Cîmpean
 
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
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming WebStackAcademy
 
(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_netNico Ludwig
 
The advantage of developing with TypeScript
The advantage of developing with TypeScript The advantage of developing with TypeScript
The advantage of developing with TypeScript Corley S.r.l.
 
Complete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScriptComplete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScriptEPAM Systems
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Gianluca Padovani
 
Moving From JavaScript to TypeScript: Things Developers Should Know
Moving From JavaScript to TypeScript: Things Developers Should KnowMoving From JavaScript to TypeScript: Things Developers Should Know
Moving From JavaScript to TypeScript: Things Developers Should KnowFibonalabs
 
Type script is awesome
Type script is awesomeType script is awesome
Type script is awesomeKeithMurgic
 
Microsoft Silverlight
Microsoft SilverlightMicrosoft Silverlight
Microsoft Silverlightguest3a8196
 

Similar to Getting started with typescript (20)

Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
 
Introduction to TypeScript by Winston Levi
Introduction to TypeScript by Winston LeviIntroduction to TypeScript by Winston Levi
Introduction to TypeScript by Winston Levi
 
Getting started with typescript and angular 2
Getting started with typescript  and angular 2Getting started with typescript  and angular 2
Getting started with typescript and angular 2
 
Type script
Type scriptType script
Type script
 
Typescript for the programmers who like javascript
Typescript for the programmers who like javascriptTypescript for the programmers who like javascript
Typescript for the programmers who like javascript
 
Typescript Basics
Typescript BasicsTypescript Basics
Typescript Basics
 
Rits Brown Bag - TypeScript
Rits Brown Bag - TypeScriptRits Brown Bag - TypeScript
Rits Brown Bag - TypeScript
 
Type script
Type scriptType script
Type script
 
Angular2
Angular2Angular2
Angular2
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
The advantage of developing with TypeScript
The advantage of developing with TypeScript The advantage of developing with TypeScript
The advantage of developing with TypeScript
 
AngularConf2015
AngularConf2015AngularConf2015
AngularConf2015
 
Complete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScriptComplete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScript
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
Moving From JavaScript to TypeScript: Things Developers Should Know
Moving From JavaScript to TypeScript: Things Developers Should KnowMoving From JavaScript to TypeScript: Things Developers Should Know
Moving From JavaScript to TypeScript: Things Developers Should Know
 
Type script is awesome
Type script is awesomeType script is awesome
Type script is awesome
 
Microsoft Silverlight
Microsoft SilverlightMicrosoft Silverlight
Microsoft Silverlight
 

Recently uploaded

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 

Recently uploaded (20)

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 

Getting started with typescript

  • 1. Microsoft Typescript BY AMINE EL HARRAK SOFTWARE ENGINEER (FULL-STACK DEVELOPER) @sqli 2017
  • 2. Agenda  Introduction  Installation & Who to use TS ?  Features  Do's and Don'ts  Conclusion
  • 4. Introduction  Introduction  How use TS ?  ***!?  Woe  Facts  Ecosystem
  • 5. Introduction  Microsoft Typescript is a statically typed compiled language to clean and a simple plain old JavaScript code which runs on any browser, in Node.js or in any JavaScript engine that supports ECMAScript 3 (or newer).
  • 6. Recent rise of TypeScript’s popularity, data from Google Trends.
  • 7. Is Anyone using Typescript ?  Angularjs2  IONIC 2  DOJO  …
  • 8. ***!? Why would I want to rewrite all of the applications I already have (Next apps) in this new language? The simple answer is you don’t have to.
  • 9. Weight of Evidence  Code is hard to navigate  Autocompletion  Refactorings  Compiler checks  debug  …
  • 10. TypeScript Facts  Large and scale application development  Language, not a framework  Cross-compiles to JavaScript  Produces idiomatic JavaScript  Doesn‘t try to replace JavaScript  Offers missing language features (Anticipates ES6, …)  Is a superset of JavaScript (Promises easy migration of JS code)  JS libs can be used easily  (Optional) static typing  …
  • 11. How to get setup ? INSTALLING TYPESCRIPT
  • 12. How to get setup ?  Installing TypeScript  Text Editors Support  Compiling to JavaScript
  • 13. Installing TypeScript There are two main ways to get the TypeScript tools:  Via npm (the Node.js package manager) / yarn add typescript  By installing TypeScript’s Visual Studio plugins.
  • 14. Installing TypeScript The easiest way to setup TypeScript is via npm. Using the command below we can install the TypeScript package globally, making the TS compiler available in all of our projects :  yarn add typescript or npm install -g typescript //For the latest stable version  npm install -g typescript@next //For our nightly builds Try opening a terminal anywhere and running tsc -v to see if it has been properly installed. $ tsc -v version 2.2.1
  • 15. Text Editors With TypeScript Support TypeScript is an open-source project but is developed and maintained by Microsoft and as such was originally supported only in Microsoft’s Visual Studio platform. Nowadays, there are a lot more text editors and IDEs that either natively or through plugins offer support for the TypeScript syntax, auto-complete suggestions, error catching, and even built-in compilers.  Visual Studio Code – Microsoft’s other, lightweight open-source code editor. TypeScript support is built in.  Official Free Plugin for Sublime Text.  The latest version of WebStorm comes with built in support.  More including Vim, Atom, Emacs and others.
  • 16. Compiling to JavaScript TypeScript is written in .ts files (or .tsx for JSX), which can’t be used directly in the browser and need to be translated to vanilla .js first. This compilation process can be done in a number of different ways:  In the terminal using the previously mentioned command line tool tsc.  Directly in Visual Studio or some of the other IDEs and text editors.  Using automated task runners such as grunt, gulp.
  • 17. Compiling to JavaScript The following command takes a TypeScript file named main.ts and translates it into its JavaScript version main.js. If main.js already exists it will be overwritten. tsc main.ts We can also compile multiple files at once by listing all of them or by applying wildcards : # Will result in separate .js files: main.js worker.js. tsc main.ts worker.ts # Compiles all .ts files in the current folder. Does NOT work recursively. tsc *.ts
  • 18. Compiling to JavaScript We can also use the --watch option to automatically compile a TypeScript file when changes are made: # Initializes a watcher process that will keep main.js up to date. tsc main.ts --watch More advanced TypeScript users can also create a tsconfig.json file, consisting of various build settings. A configuration file is very handy when working on large projects with lots of .ts files since it somewhat automates the process. You can read more about tsconfig.json in the TypeScript docs.
  • 20. Language Features  Type annotations  Type inference  Compile time type checking  Optional, default and rest parameters  Classes  Interfaces  Structural typing  Arrow function expressions  Enums  Generics  Modules  Tuple types  Union types and type guards
  • 22. Class class Person { protected name: string; constructor(name: string) { this.name = name; } } class Employee extends Person { private department: string; constructor(name: string, department: string) { super(name); this.department = department; } public getElevatorPitch() { return `Hello, my name is ${this.name} and I work in ${this.department}.`; } } let howard = new Employee("Howard", "Sales"); console.log(howard.getElevatorPitch()); console.log(howard.name); // error
  • 23. Interfaces interface ClockInterface { currentTime: Date; setTime(d: Date); } class Clock implements ClockInterface { currentTime: Date; setTime(d: Date) { this.currentTime = d; } constructor(h: number, m: number) { } }
  • 24. Generics function identity<T>(arg: T): T { return arg; } let output = identity<string>("myString"); // type of output will be 'string'
  • 25. Enums const enum Directions { Up, Down, Left, Right } let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right]
  • 27. Modules //Validation.ts export interface StringValidator { isAcceptable(s: string): boolean; } //ZipCodeValidator.ts export const numberRegexp = /^[0-9]+$/; export class ZipCodeValidator implements StringValidator { isAcceptable(s: string) { return s.length === 5 && numberRegexp.test(s); } }
  • 29. Do's and Don'ts |General Types Don’t ever use the types Number, String, Boolean, or Object. These types refer to non-primitive boxed objects that are almost never used appropriately in JavaScript code. /* WRONG */ function reverse(s: String): String; /* OK */ function reverse(s: string): string; If you’re tempted to use the type Object, consider using any instead. There is currently no way in TypeScript to specify an object that is “not a primitive”.
  • 30. Do's and Don'ts |Callback Types Don’t use the return type any for callbacks whose value will be ignored: /* WRONG */ function fn(x: () => any) { x(); } /* OK */ function fn(x: () => void) { x(); }
  • 31. Do's and Don'ts |Callback Types Example : function fn(x: () => void) { var k = x(); // oops! meant to do something else k.doSomething(); // error, but would be OK if the return type had been 'any‘ } Why: Using void is safer because it prevents you from accidently using the return value of x in an unchecked way
  • 32. Do's and Don'ts |Overloads and Callbacks Don’t write separate overloads that differ only on callback arity -> Do write a single overload using the maximum arity: /* WRONG */ declare function beforeAll(action: () => void, timeout?: number): void; declare function beforeAll(action: (done: DoneFn) => void, timeout?: number): void; /* OK */ declare function beforeAll(action: (done: DoneFn) => void, timeout?: number): void;
  • 33. Do's and Don'ts |Function Overloads Don’t put more general overloads before more specific overloads, Do sort overloads by putting the more general signatures after more specific signatures: /* WRONG */ declare function fn(x: any): any; declare function fn(x: HTMLElement): number; declare function fn(x: HTMLDivElement): string; var myElem: HTMLDivElement; var x = fn(myElem); // x: any, wat? /* OK */ declare function fn(x: HTMLDivElement): string; declare function fn(x: HTMLElement): number; declare function fn(x: any): any; var myElem: HTMLDivElement; var x = fn(myElem); // x: string, Why: TypeScript chooses the first matching overload when resolving function calls. When an earlier overload is “more general” than a later one, the later one is effectively hidden and cannot be called.
  • 34. Do's and Don'ts |Use Optional Parameters Don’t write several overloads that differ only in trailing parameters, Do use optional parameters whenever possible: /* WRONG */ interface Example { diff(one: string): number; diff(one: string, two: string): number; diff(one: string, two: string, three: boolean): number; } /* OK */ interface Example { diff(one: string, two?: string, three?: boolean): number; } Why: TypeScript chooses the first matching overload when resolving function calls. When an earlier overload is “more general” than a later one, the later one is effectively hidden and cannot be called.
  • 35. Do's and Don'ts |Use Union Types Don’t write overloads that differ by type in only one argument position, Do use union types whenever possible: /* WRONG */ interface Moment { utcOffset(): number; utcOffset(b: number): Moment; utcOffset(b: string): Moment; } /* OK */ interface Moment { utcOffset(): number; utcOffset(b: number|string): Moment; } Note that we didn’t make b optional here because the return types of the signatures differ.
  • 37. Step projectRoot ├── src │ ├── file1.js │ └── file2.js ├── built └── tsconfig.json 1. Setting up your Directories 2. Writing a Configuration File 3. Integrating with Build Tools (Gulp, Webpack …) { "compilerOptions": { "outDir": "./built", "allowJs": true, "target": "es5" }, "include": [ "./src/**/*" ] }

Editor's Notes

  1. Pourquoi: Utiliser void est plus sûr car il vous empêche d'utiliser accidentellement la valeur de retour de x d'une manière non contrôlée:
  2. Pourquoi: Utiliser void est plus sûr car il vous empêche d'utiliser accidentellement la valeur de retour de x d'une manière non contrôlée:
  3. Pourquoi: TypeScript choisit la première surcharge correspondante lors de la résolution des appels de fonction. Lorsqu'une surcharge antérieure est «plus générale» qu'une dernière, la dernière est effectivement masquée et ne peut pas être appelée.
  4. Pourquoi: Cela est important pour les personnes qui «passent par» une valeur à votre fonction
  5. Pourquoi: Cela est important pour les personnes qui «passent par» une valeur à votre fonction