Getting started with typescript

38
Microsoft Typescript BY AMINE EL HARRAK SOFTWARE ENGINEER (FULL-STACK DEVELOPER) @sqli 2017

Transcript of Getting started with typescript

Page 1: Getting started with typescript

Microsoft TypescriptBY AMINE EL HARRAK

SOFTWARE ENGINEER (FULL-STACK DEVELOPER) @sqli 2017

Page 2: Getting started with typescript

Agenda

Introduction Installation & Who to use TS ? Features Do's and Don'ts Conclusion

Page 3: Getting started with typescript

Introduction JAVASCRIPT THAT SCALES.

Page 4: Getting started with typescript

Introduction

Introduction How use TS ? ***!? Woe Facts Ecosystem

Page 5: Getting started with typescript

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).

Page 6: Getting started with typescript

Recent rise of TypeScript’s popularity, data from Google Trends.

Page 7: Getting started with typescript

Is Anyone using Typescript ?

Angularjs2 IONIC 2 DOJO …

Page 8: Getting started with typescript

***!?

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.

Page 9: Getting started with typescript

Weight of Evidence

Code is hard to navigate Autocompletion Refactorings Compiler checks debug …

Page 10: Getting started with typescript

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 …

Page 11: Getting started with typescript

How to get setup ? INSTALLING TYPESCRIPT

Page 12: Getting started with typescript

How to get setup ?

Installing TypeScript Text Editors Support Compiling to JavaScript

Page 13: Getting started with typescript

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.

Page 14: Getting started with typescript

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 buildsTry opening a terminal anywhere and running tsc -v to see if it has been properly installed.$ tsc -vversion 2.2.1

Page 15: Getting started with typescript

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.

Page 16: Getting started with typescript

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.

Page 17: Getting started with typescript

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.tsWe 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

Page 18: Getting started with typescript

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.

Page 19: Getting started with typescript

Features of TypeScript

Page 20: Getting started with 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

Page 21: Getting started with typescript

TypeScript grammar

Page 22: Getting started with typescript

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

Page 23: Getting started with typescript

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) { }}

Page 24: Getting started with typescript

Generics

function identity<T>(arg: T): T { return arg;}

let output = identity<string>("myString"); // type of output will be 'string'

Page 25: Getting started with typescript

Enums

const enum Directions { Up, Down, Left, Right}

let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right]

Page 26: Getting started with typescript

Examples

Page 27: Getting started with typescript

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); }}

Page 28: Getting started with typescript

Do's and Don'ts

Page 29: Getting started with typescript

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”.

Page 30: Getting started with typescript

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();}

Page 31: Getting started with typescript

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

Page 32: Getting started with typescript

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;

Page 33: Getting started with typescript

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.

Page 34: Getting started with typescript

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.

Page 35: Getting started with typescript

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.

Page 36: Getting started with typescript

Migrating from JavaScript

Page 37: Getting started with typescript

Step

projectRoot├── src│ ├── file1.js│ └── file2.js├── built└── tsconfig.json

1. Setting up your Directories2. Writing a Configuration File3. Integrating with Build Tools (Gulp,

Webpack …){ "compilerOptions": { "outDir": "./built", "allowJs": true, "target": "es5" }, "include": [ "./src/**/*" ]}

Page 38: Getting started with typescript

”Thank you !