INTRODUCTION TO TYPESCRIPT ANDRÉ PITOMBEIRA
AGENDA ▸ Introduction ▸ Configuration ▸ Language Features ▸ Code Organisation ▸ The Type System
ANY APPLICATION THAT CAN BE WRITTEN IN JAVASCRIPT WILL EVENTUALLY BE WRITTEN IN JAVASCRIPT. Jeff Atwood INTRODUCTION
INTRODUCTION WHAT IS GOOD ABOUT JAVASCRIPT? ▸ It is everywhere ▸ Huge amount of libraries ▸ Flexible (small learning curve) ▸ Enhancing web pages ▸ Data entry validations ▸ Single page applications
INTRODUCTION WHAT IS BAD ABOUT JAVASCRIPT? ▸ Equality and Type Juggling ▸ Lack of modularity ▸ Prototypal inheritance ▸ Scope ▸ Lack of Types ▸ Design errors ▸ Lousy and inconsistent implementations ▸ Challenging to manage large projects
INTRODUCTION WHAT IS BAD ABOUT JAVASCRIPT? const num = 1; const str = '0'; // result is '10' and not 1 const strTen = num + str; // result is 20 const result = strTen * 2;
INTRODUCTION WHY TYPESCRIPT? ▸ It is an open source language created and maintained by Microsoft (2012) ▸ The language is focused on making the development of JavaScript applications to many thousands lines of code ▸ The language offers better design-time tooling, compile time checking and dynamic module loading at runtime ▸ Applications written in TypeScript: Azure Management Portal (1.2 million lines of code) and VS Code (300,000 lines of code)
INTRODUCTION TYPESCRIPT DESIGN GOALS ▸ The TypeScript language is a typed superset of JavaScript ▸ Adds support for classes, interfaces, generics and modules ▸ Development tooling support ▸ Compiled JavaScript run in any browser (or Node.js) ▸ Since JavaScript code is TypeScript code you can start off with JavaScript and just add some types here and there
INTRODUCTION FRAMEWORKS WRITTEN IN TYPESCRIPT
INTRODUCTION IDES WITH SUPPORT TO TYPESCRIPT
CONFIGURATION INSTALLING AND RUNNING THE TYPESCRIPT COMPILER $ yarn global add typescript $ npm install -g typescript $ tsc -v $ tsc <file.ts>
CONFIGURATION CONFIGURING A NEW TYPESCRIPT PROJECT $ tsc - -init { "compilerOptions": { /* Basic Options */ "target": “es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ "module": “es2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ "strict": true, /* Enable all strict type-checking options. */ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ } }
LANGUAGE FEATURES BASIC TYPES Boolean: let isDone: boolean = false; Number: let decimal: number = 6; String: let colour: string = “blue"; Array: let list: number[] = [1, 2, 3]; Tuple: let x: [string, number]; Enum: enum Colour { Red, Green, Blue } Any: let notSure: any = 4;
LANGUAGE FEATURES BASIC TYPES void: function warnUser(): void { console.log("This is my warning message"); } Null and Undefined: let u: undefined = undefined; let n: null = null; Never: function error(message: string): never { throw new Error(message); } Object: let obj: object = {};
LANGUAGE FEATURES INTERFACES ▸ Duck Typing ▸ Defining contracts interface LabelledValue { label: string; } interface SquareConfig { color?: string; width?: number; } interface Point { readonly x: number; readonly y: number; } interface SearchFunc { (source: string, subString: string): boolean; }
LANGUAGE FEATURES INTERFACES interface Shape { color: string; } interface Square extends Shape { sideLength: number; } interface ClockInterface { currentTime: Date; } class Clock implements ClockInterface { currentTime: Date; constructor(h: number, m: number) { } }
LANGUAGE FEATURES CLASSES ▸ Prototype-based inheritance ▸ Object-oriented approach ▸ ECMASCRIPT 6 ▸ Class based approach class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } let greeter = new Greeter("world");
LANGUAGE FEATURES CLASSES - INHERITANCE class Animal { move(distanceInMeters: number = 0) { console.log(`Animal moved ${distanceInMeters}m.`); } } class Dog extends Animal { bark() { console.log('Woof! Woof!'); } } const dog = new Dog(); dog.bark(); dog.move(10); dog.bark();
LANGUAGE FEATURES CLASSES - MODIFIERS ACCESS ▸ Public ▸ Private ▸ Protected class Animal { private name: string; constructor(theName: string) { this.name = theName; } }
LANGUAGE FEATURES CLASSES - ABSTRACT abstract class Animal { abstract makeSound(): void; move(): void { console.log("roaming the earth..."); } }
LANGUAGE FEATURES CLASSES - STATIC class Grid { static origin = {x: 0, y: 0}; calculateDistanceFromOrigin(point: {x: number; y: number;}) { let xDist = (point.x - Grid.origin.x); let yDist = (point.y - Grid.origin.y); return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale; } constructor (public scale: number) { } }
LANGUAGE FEATURES GENERICS ▸ Reusable components ▸ Languages like Java and C# implement Generics function identity<T>(arg: T): T { return arg; } function getProperty<T, K extends keyof T>(obj: T, key: K) { return obj[key]; } function createInstance<A extends Animal>(c: new () => A): A { return new c(); }
LANGUAGE FEATURES ENUM ▸ Define a set of named constants ▸ Easier to document intent enum Response { No = 0, Yes = 1, } function respond(recipient: string, message: Response): void { // ... } respond("Princess Caroline", Response.Yes)
IT IS NOT THE LANGUAGE THAT MAKES PROGRAMS APPEAR SIMPLE. IT IS THE PROGRAMER THAT MAKES THE LANGUAGE APPEAR SIMPLE! Robert C Martin CODE ORGANISATION
CODE ORGANISATION MODULES ▸ Modules are executed within their own scope, not in the global scope ▸ Everything declared are not visible outside the module unless they’re explicitly exported export interface StringValidator { isAcceptable(s: string): boolean; } export const numberRegexp = /^[0-9]+$/; export class ZipCodeValidator implements StringValidator { isAcceptable(s: string) { return s.length === 5 && numberRegexp.test(s); } }
CODE ORGANISATION NAMESPACE ▸ Organise related files ▸ Avoid name collisions namespace Validation { export interface StringValidator { isAcceptable(s: string): boolean; } const lettersRegexp = /^[A-Za-z]+$/; const numberRegexp = /^[0-9]+$/; export class LettersOnlyValidator implements StringValidator { isAcceptable(s: string) { return lettersRegexp.test(s); } } export class ZipCodeValidator implements StringValidator { isAcceptable(s: string) { return s.length === 5 && numberRegexp.test(s); } } }
CODE ORGANISATION DECORATORS { "compilerOptions": { "target": "ES5", "experimentalDecorators": true } } function log(target: any, key, string, descriptor: any) { console.log(key); } class Calculator { @log square(n: number) { return n * n; } }
THE TYPE SYSTEM ▸ Type systems is originate from type theory ▸ Type theory is a system in which each term is given a type and operations are restricted based on types ▸ In general, a type system assigns a type to each variable, expression, object, function, class or module in the system ▸ Typical rules ensures that the value used in the assignment is the same type as the variable it is being assigned to, or the functions arguments have the right type
THE TYPE SYSTEM ▸ Optional Static Types ▸ Structural Typing ▸ Type Erasure ▸ Type Inference ▸ Type Checking
THE TYPE SYSTEM LET’S CODE!
QUESTIONS?
THANK YOU

Introduction to TypeScript

  • 1.
  • 2.
    AGENDA ▸ Introduction ▸ Configuration ▸Language Features ▸ Code Organisation ▸ The Type System
  • 3.
    ANY APPLICATION THATCAN BE WRITTEN IN JAVASCRIPT WILL EVENTUALLY BE WRITTEN IN JAVASCRIPT. Jeff Atwood INTRODUCTION
  • 4.
    INTRODUCTION WHAT IS GOODABOUT JAVASCRIPT? ▸ It is everywhere ▸ Huge amount of libraries ▸ Flexible (small learning curve) ▸ Enhancing web pages ▸ Data entry validations ▸ Single page applications
  • 5.
    INTRODUCTION WHAT IS BADABOUT JAVASCRIPT? ▸ Equality and Type Juggling ▸ Lack of modularity ▸ Prototypal inheritance ▸ Scope ▸ Lack of Types ▸ Design errors ▸ Lousy and inconsistent implementations ▸ Challenging to manage large projects
  • 6.
    INTRODUCTION WHAT IS BADABOUT JAVASCRIPT? const num = 1; const str = '0'; // result is '10' and not 1 const strTen = num + str; // result is 20 const result = strTen * 2;
  • 7.
    INTRODUCTION WHY TYPESCRIPT? ▸ Itis an open source language created and maintained by Microsoft (2012) ▸ The language is focused on making the development of JavaScript applications to many thousands lines of code ▸ The language offers better design-time tooling, compile time checking and dynamic module loading at runtime ▸ Applications written in TypeScript: Azure Management Portal (1.2 million lines of code) and VS Code (300,000 lines of code)
  • 8.
    INTRODUCTION TYPESCRIPT DESIGN GOALS ▸The TypeScript language is a typed superset of JavaScript ▸ Adds support for classes, interfaces, generics and modules ▸ Development tooling support ▸ Compiled JavaScript run in any browser (or Node.js) ▸ Since JavaScript code is TypeScript code you can start off with JavaScript and just add some types here and there
  • 9.
  • 10.
  • 11.
    CONFIGURATION INSTALLING AND RUNNINGTHE TYPESCRIPT COMPILER $ yarn global add typescript $ npm install -g typescript $ tsc -v $ tsc <file.ts>
  • 12.
    CONFIGURATION CONFIGURING A NEWTYPESCRIPT PROJECT $ tsc - -init { "compilerOptions": { /* Basic Options */ "target": “es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ "module": “es2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ "strict": true, /* Enable all strict type-checking options. */ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ } }
  • 13.
    LANGUAGE FEATURES BASIC TYPES Boolean:let isDone: boolean = false; Number: let decimal: number = 6; String: let colour: string = “blue"; Array: let list: number[] = [1, 2, 3]; Tuple: let x: [string, number]; Enum: enum Colour { Red, Green, Blue } Any: let notSure: any = 4;
  • 14.
    LANGUAGE FEATURES BASIC TYPES void: functionwarnUser(): void { console.log("This is my warning message"); } Null and Undefined: let u: undefined = undefined; let n: null = null; Never: function error(message: string): never { throw new Error(message); } Object: let obj: object = {};
  • 15.
    LANGUAGE FEATURES INTERFACES ▸ DuckTyping ▸ Defining contracts interface LabelledValue { label: string; } interface SquareConfig { color?: string; width?: number; } interface Point { readonly x: number; readonly y: number; } interface SearchFunc { (source: string, subString: string): boolean; }
  • 16.
    LANGUAGE FEATURES INTERFACES interface Shape{ color: string; } interface Square extends Shape { sideLength: number; } interface ClockInterface { currentTime: Date; } class Clock implements ClockInterface { currentTime: Date; constructor(h: number, m: number) { } }
  • 17.
    LANGUAGE FEATURES CLASSES ▸ Prototype-basedinheritance ▸ Object-oriented approach ▸ ECMASCRIPT 6 ▸ Class based approach class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } let greeter = new Greeter("world");
  • 18.
    LANGUAGE FEATURES CLASSES -INHERITANCE class Animal { move(distanceInMeters: number = 0) { console.log(`Animal moved ${distanceInMeters}m.`); } } class Dog extends Animal { bark() { console.log('Woof! Woof!'); } } const dog = new Dog(); dog.bark(); dog.move(10); dog.bark();
  • 19.
    LANGUAGE FEATURES CLASSES -MODIFIERS ACCESS ▸ Public ▸ Private ▸ Protected class Animal { private name: string; constructor(theName: string) { this.name = theName; } }
  • 20.
    LANGUAGE FEATURES CLASSES -ABSTRACT abstract class Animal { abstract makeSound(): void; move(): void { console.log("roaming the earth..."); } }
  • 21.
    LANGUAGE FEATURES CLASSES -STATIC class Grid { static origin = {x: 0, y: 0}; calculateDistanceFromOrigin(point: {x: number; y: number;}) { let xDist = (point.x - Grid.origin.x); let yDist = (point.y - Grid.origin.y); return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale; } constructor (public scale: number) { } }
  • 22.
    LANGUAGE FEATURES GENERICS ▸ Reusablecomponents ▸ Languages like Java and C# implement Generics function identity<T>(arg: T): T { return arg; } function getProperty<T, K extends keyof T>(obj: T, key: K) { return obj[key]; } function createInstance<A extends Animal>(c: new () => A): A { return new c(); }
  • 23.
    LANGUAGE FEATURES ENUM ▸ Definea set of named constants ▸ Easier to document intent enum Response { No = 0, Yes = 1, } function respond(recipient: string, message: Response): void { // ... } respond("Princess Caroline", Response.Yes)
  • 24.
    IT IS NOTTHE LANGUAGE THAT MAKES PROGRAMS APPEAR SIMPLE. IT IS THE PROGRAMER THAT MAKES THE LANGUAGE APPEAR SIMPLE! Robert C Martin CODE ORGANISATION
  • 25.
    CODE ORGANISATION MODULES ▸ Modulesare executed within their own scope, not in the global scope ▸ Everything declared are not visible outside the module unless they’re explicitly exported export interface StringValidator { isAcceptable(s: string): boolean; } export const numberRegexp = /^[0-9]+$/; export class ZipCodeValidator implements StringValidator { isAcceptable(s: string) { return s.length === 5 && numberRegexp.test(s); } }
  • 26.
    CODE ORGANISATION NAMESPACE ▸ Organiserelated files ▸ Avoid name collisions namespace Validation { export interface StringValidator { isAcceptable(s: string): boolean; } const lettersRegexp = /^[A-Za-z]+$/; const numberRegexp = /^[0-9]+$/; export class LettersOnlyValidator implements StringValidator { isAcceptable(s: string) { return lettersRegexp.test(s); } } export class ZipCodeValidator implements StringValidator { isAcceptable(s: string) { return s.length === 5 && numberRegexp.test(s); } } }
  • 27.
    CODE ORGANISATION DECORATORS { "compilerOptions": { "target":"ES5", "experimentalDecorators": true } } function log(target: any, key, string, descriptor: any) { console.log(key); } class Calculator { @log square(n: number) { return n * n; } }
  • 28.
    THE TYPE SYSTEM ▸Type systems is originate from type theory ▸ Type theory is a system in which each term is given a type and operations are restricted based on types ▸ In general, a type system assigns a type to each variable, expression, object, function, class or module in the system ▸ Typical rules ensures that the value used in the assignment is the same type as the variable it is being assigned to, or the functions arguments have the right type
  • 29.
    THE TYPE SYSTEM ▸Optional Static Types ▸ Structural Typing ▸ Type Erasure ▸ Type Inference ▸ Type Checking
  • 30.
  • 31.
  • 32.