Docsity

Programacion typescript, Esquemas y mapas conceptuales de Programación Javascript

Toggle sidebar
bg1
TypeScript
Notes for Professionals
TypeScript
Notes for Professionals
GoalKicker.com
Free Programming Books
Disclaimer
This is an unocial free book created for educational purposes and is
not aliated with ocial TypeScript group(s) or company(s).
All trademarks and registered trademarks are
the property of their respective owners
80+ pages
of professional hints and tricks
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61

Vista previa parcial del texto

¡Descarga Programacion typescript y más Esquemas y mapas conceptuales en PDF de Programación Javascript solo en Docsity!

TypeScript

Notes for Professionals

TypeScript

Notes for Professionals

GoalKicker.com

Free Programming Books

Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial TypeScript group(s) or company(s). All trademarks and registered trademarks are the property of their respective owners

80+ pages

of professional hints and tricks

Contents

About

Please feel free to share this PDF with anyone for free, latest version of this book can be downloaded from: https://goalkicker.com/TypeScriptBook

This TypeScript Notes for Professionals book is compiled from Stack Overflow

Documentation, the content is written by the beautiful people at Stack Overflow.

Text content is released under Creative Commons BY-SA, see credits at the end

of this book whom contributed to the various chapters. Images may be copyright

of their respective owners unless otherwise specified

This is an unofficial free book created for educational purposes and is not

affiliated with official TypeScript group(s) or company(s) nor Stack Overflow. All

trademarks and registered trademarks are the property of their respective

company owners

The information presented in this book is not guaranteed to be correct nor

accurate, use at your own risk

Please send feedback and corrections to [email protected]

IDEs

Visual Studio

Visual Studio 2015 includes TypeScript.

Visual Studio 2013 Update 2 or later includes TypeScript, or you can download TypeScript for earlier

versions.

Visual Studio Code

Visual Studio Code (vscode) provides contextual autocomplete as well as refactoring and debugging tools for

TypeScript. vscode is itself implemented in TypeScript. Available for Mac OS X, Windows and Linux.

WebStorm

WebStorm 2016.2 comes with TypeScript and a built-in compiler. [WebStorm is not free]

IntelliJ IDEA

IntelliJ IDEA 2016.2 has support for TypeScript and a compiler via a plugin maintained by the JetBrains

team. [IntelliJ is not free]

Atom & atom-typescript

Atom supports TypeScript with the atom-typescript package.

Sublime Text

Sublime Text supports TypeScript with the TypeScript package.

Installing the command line interface

Install Node.js

Install the npm package globally

You can install TypeScript globally to have access to it from any directory.

npm install -g typescript

or

Install the npm package locally

You can install TypeScript locally and save to package.json to restrict to a directory.

npm install typescript --save-dev Installation channels

You can install from:

Stable channel: npm install typescript

Beta channel: npm install typescript @ beta

Dev channel: npm install typescript @ next

Compiling TypeScript code

The tsc compilation command comes with typescript, which can be used to compile code.

tsc my-code.ts

This creates a my-code.js file.

Compile using tsconfig.json

You can also provide compilation options that travel with your code via a tsconfig.json file. To start a new

TypeScript project, cd into your project's root directory in a terminal window and run tsc --init. This command

will generate a tsconfig.json file with minimal configuration options, similar to below.

"compilerOptions": { "module": "commonjs", "target": "es5", "noImplicitAny": false , "sourceMap": false , "pretty": true }, "exclude": [ "node_modules" ] }

With a tsconfig.json file placed at the root of your TypeScript project, you can use the tsc command to run the

compilation.

Section 1.2: Basic syntax

TypeScript is a typed superset of JavaScript, which means that all JavaScript code is valid TypeScript code. TypeScript

adds a lot of new features on top of that.

TypeScript makes JavaScript more like a strongly-typed, object-oriented language akin to C# and Java. This means

that TypeScript code tends to be easier to use for large projects and that code tends to be easier to understand and

maintain. The strong typing also means that the language can (and is) precompiled and that variables cannot be

assigned values that are out of their declared range. For instance, when a TypeScript variable is declared as a

number, you cannot assign a text value to it.

This strong typing and object orientation makes TypeScript easier to debug and maintain, and those were two of

the weakest points of standard JavaScript.

Type declarations

You can add type declarations to variables, function parameters and function return types. The type is written after

a colon following the variable name, like this: var num: number = 5; The compiler will then check the types (where

possible) during compilation and report type errors.

var num: number = 5; num = "this is a string"; // error: Type 'string' is not assignable to type 'number'.

The basic types are :

number (both integers and floating point numbers)

string boolean

Array. You can specify the types of an array's elements. There are two equivalent ways to define array types:

Array and T[]. For example:

number[] - array of numbers

Array - array of strings

Tuples. Tuples have a fixed number of elements with specific types.

[boolean, string] - tuple where the first element is a boolean and the second is a string.

[number, number, number] - tuple of three numbers.

let greeter = new Greeter("Hello, world!"); console.log(greeter.greet());

Here we have a class, Greeter, that has a constructor and a greet method. We can construct an instance of the

class using the new keyword and pass in a string we want the greet method to output to the console. The instance

of our Greeter class is stored in the greeter variable which we then us to call the greet method.

Section 1.4: Running TypeScript using ts-node

ts-node is an npm package which allows the user to run typescript files directly, without the need for

precompilation using tsc. It also provides REPL.

Install ts-node globally using

npm install -g ts-node

ts-node does not bundle typescript compiler, so you might need to install it.

npm install -g typescript

Executing script

To execute a script named main.ts , run

ts-node main.ts

// main.ts console.log("Hello world");

Example usage

$ ts-node main.ts Hello world

Running REPL

To run REPL run command ts-node

Example usage

$ ts-node

const sum = (a, b): number => a + b; undefined sum(2, 2) 4 .exit

To exit REPL use command .exit or press CTRL+C twice.

Section 1.5: TypeScript REPL in Node.js

For use TypeScript REPL in Node.js you can use tsun package

Install it globally with

npm install -g tsun

and run in your terminal or command prompt with tsun command

Usage example:

$ tsun TSUN : TypeScript Upgraded Node type in TypeScript expression to evaluate type :help for commands in repl $ function multiply(x, y) { .. return x * y; ..} undefined $ multiply(3, 4) 12

Chapter 3: TypeScript Core Types

Section 3.1: String Literal Types

String literal types allow you to specify the exact value a string can have.

let myFavoritePet: "dog"; myFavoritePet = "dog";

Any other string will give an error.

// Error: Type '"rock"' is not assignable to type '"dog"'. // myFavoritePet = "rock";

Together with Type Aliases and Union Types you get a enum-like behavior.

type Species = "cat" | "dog" | "bird";

function buyPet(pet: Species, name: string) : Pet { /.../ }

buyPet(myFavoritePet /* "dog" as defined above */ , "Rocky");

// Error: Argument of type '"rock"' is not assignable to parameter of type "'cat' | "dog" | "bird". Type '"rock"' is not assignable to type '"bird"'. // buyPet("rock", "Rocky");

String Literal Types can be used to distinguish overloads.

function buyPet(pet: Species, name: string) : Pet; function buyPet(pet: "cat", name: string): Cat; function buyPet(pet: "dog", name: string): Dog; function buyPet(pet: "bird", name: string): Bird; function buyPet(pet: Species, name: string) : Pet { /.../ }

let dog = buyPet(myFavoritePet /* "dog" as defined above */ , "Rocky"); // dog is from type Dog (dog: Dog)

They works well for User-Defined Type Guards.

interface Pet { species: Species; eat(); sleep(); }

interface Cat extends Pet { species: "cat"; }

interface Bird extends Pet { species: "bird"; sing(); }

function petIsCat(pet: Pet): pet is Cat { return pet.species === "cat"; }

function petIsBird(pet: Pet): pet is Bird { return pet.species === "bird"; }

function playWithPet(pet: Pet){ if (petIsCat(pet)) { // pet is now from type Cat (pet: Cat) pet.eat(); pet.sleep(); } else if (petIsBird(pet)) { // pet is now from type Bird (pet: Bird) pet.eat(); pet.sing(); pet.sleep(); } }

Full example code

let myFavoritePet: "dog"; myFavoritePet = "dog";

// Error: Type '"rock"' is not assignable to type '"dog"'. // myFavoritePet = "rock";

type Species = "cat" | "dog" | "bird";

interface Pet { species: Species; name: string; eat(); walk(); sleep(); }

interface Cat extends Pet { species: "cat"; }

interface Dog extends Pet { species: "dog"; }

interface Bird extends Pet { species: "bird"; sing(); }

// Error: Interface 'Rock' incorrectly extends interface 'Pet'. Types of property 'species' are incompatible. Type '"rock"' is not assignable to type '"cat" | "dog" | "bird"'. Type '"rock"' is not assignable to type '"bird"'. // interface Rock extends Pet { // type: "rock"; // }

function buyPet(pet: Species, name: string) : Pet; function buyPet(pet: "cat", name: string): Cat; function buyPet(pet: "dog", name: string): Dog; function buyPet(pet: "bird", name: string): Bird; function buyPet(pet: Species, name: string) : Pet { if (pet === "cat") {

// Error: Type '"bird"' is not assignable to type '"cat"'. // pet.type = "bird";

// Error: Property 'sing' does not exist on type 'Cat'. // pet.sing();

} else if (petIsDog(pet)) { // pet is now from type Dog (pet: Dog)

pet.eat(); pet.walk(); pet.sleep();

} else if (petIsBird(pet)) { // pet is now from type Bird (pet: Bird)

pet.eat(); pet.sing(); pet.sleep(); } else { throw "An unknown pet. Did you buy a rock?"; } }

let dog = buyPet(myFavoritePet /* "dog" as defined above */ , "Rocky"); // dog is from type Dog (dog: Dog)

// Error: Argument of type '"rock"' is not assignable to parameter of type "'cat' | "dog" | "bird". Type '"rock"' is not assignable to type '"bird"'. // buyPet("rock", "Rocky");

playWithPet(dog); // Output: Hey Rocky, lets play. // Rocky eats. // Rocky walks. // Rocky sleeps.

Section 3.2: Tuple

Array type with known and possibly different types:

let day: [number, string]; day = [0, 'Monday']; // valid day = ['zero', 'Monday']; // invalid: 'zero' is not numeric console.log(day[0]); // 0 console.log(day[1]); // Monday

day[2] = 'Saturday'; // valid: [0, 'Saturday'] day[3] = false ; // invalid: must be union type of 'number | string'

Section 3.3: Boolean

A boolean represents the most basic datatype in TypeScript, with the purpose of assigning true/false values.

// set with initial value (either true or false) let isTrue: boolean = true ;

// defaults to 'undefined', when not explicitly set let unsetBool: boolean;

// can also be set to 'null' as well let nullableBool: boolean = null ;

Section 3.4: Intersection Types

A Intersection Type combines the member of two or more types.

interface Knife { cut(); }

interface BottleOpener{ openBottle(); }

interface Screwdriver{ turnScrew(); }

type SwissArmyKnife = Knife & BottleOpener & Screwdriver;

function use(tool: SwissArmyKnife){ console.log("I can do anything!");

tool.cut(); tool.openBottle(); tool.turnScrew(); }

Section 3.5: Types in function arguments and return value.

Number

When you create a function in TypeScript you can specify the data type of the function's arguments and the data

type for the return value

Example:

function sum(x: number, y: number): number { return x + y; }

Here the syntax x: number, y: number means that the function can accept two argumentsx and y and they can

only be numbers and (...): number { means that the return value can only be a number

Usage:

sum(84 + 76) // will be return 160

Note:

You can not do so

function sum(x: string, y: string): number { return x + y; }

or

For comparison, a normal Enum

// TypeScript: A normal Enum enum PirateActivity { Boarding, Drinking, Fencing }

// JavaScript: The Enum after the compiling // var PirateActivity; // (function (PirateActivity) { // PirateActivity[PirateActivity["Boarding"] = 0] = "Boarding"; // PirateActivity[PirateActivity["Drinking"] = 1] = "Drinking"; // PirateActivity[PirateActivity["Fencing"] = 2] = "Fencing"; // })(PirateActivity || (PirateActivity = {}));

// TypeScript: A normal use of this Enum let myFavoritePirateActivity = PirateActivity.Boarding; console.log(myFavoritePirateActivity); // 0

// JavaScript: Looks quite similar in JavaScript // var myFavoritePirateActivity = PirateActivity.Boarding; // console.log(myFavoritePirateActivity); // 0

// TypeScript: And some other normal use console.log(PirateActivity["Drinking"]); // 1

// JavaScript: Looks quite similar in JavaScript // console.log(PirateActivity["Drinking"]); // 1

// TypeScript: At runtime, you can access an normal enum console.log(PirateActivity[myFavoritePirateActivity]); // "Boarding"

// JavaScript: And it will be resolved at runtime // console.log(PirateActivity[myFavoritePirateActivity]); // "Boarding"

Section 3.8: Number

Like JavaScript, numbers are floating point values.

let pi: number = 3.14; // base 10 decimal by default let hexadecimal: number = 0xFF; // 255 in decimal

ECMAScript 2015 allows binary and octal.

let binary: number = 0b10; // 2 in decimal let octal: number = 0o755; // 493 in decimal

Section 3.9: String

Textual data type:

let singleQuotes: string = 'single'; let doubleQuotes: string = "double"; let templateString: string = I am ${ singleQuotes }; // I am single

Section 3.10: Array

An array of values:

let threePigs: number[] = [1, 2, 3]; let genericStringArray: Array = ['first', '2nd', '3rd'];

Section 3.11: Enum

A type to name a set of numeric values:

Number values default to 0:

enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }; let bestDay: Day = Day.Saturday;

Set a default starting number:

enum TenPlus { Ten = 10, Eleven, Twelve }

or assign values:

enum MyOddSet { Three = 3, Five = 5, Seven = 7, Nine = 9 }

Section 3.12: Any

When unsure of a type, any is available:

let anything: any = 'I am a string'; anything = 5; // but now I am the number 5

Section 3.13: Void

If you have no type at all, commonly used for functions that do not return anything:

function log(): void { console.log('I return nothing'); }

void types Can only be assigned null or undefined.