

























































































Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!


























































































GoalKicker.com
Free Programming Books
Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial TypeScript group(s) or company(s). All trademarks and registered trademarks are the property of their respective owners
of professional hints and tricks
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
npm install -g typescript
tsc my-code.ts
"compilerOptions": { "module": "commonjs", "target": "es5", "noImplicitAny": false , "sourceMap": false , "pretty": true }, "exclude": [ "node_modules" ] }
Section 1.2: Basic syntax
var num: number = 5; num = "this is a string"; // error: Type 'string' is not assignable to type 'number'.
string boolean
let greeter = new Greeter("Hello, world!"); console.log(greeter.greet());
Section 1.4: Running TypeScript using ts-node
npm install -g ts-node
npm install -g typescript
ts-node main.ts
// main.ts console.log("Hello world");
$ ts-node main.ts Hello world
$ ts-node
const sum = (a, b): number => a + b; undefined sum(2, 2) 4 .exit
Section 1.5: TypeScript REPL in Node.js
npm install -g tsun
$ 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
let myFavoritePet: "dog"; myFavoritePet = "dog";
// Error: Type '"rock"' is not assignable to type '"dog"'. // myFavoritePet = "rock";
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");
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)
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(); } }
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
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
// 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
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
function sum(x: number, y: number): number { return x + y; }
sum(84 + 76) // will be return 160
function sum(x: string, y: string): number { return x + y; }
// 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
let pi: number = 3.14; // base 10 decimal by default let hexadecimal: number = 0xFF; // 255 in decimal
let binary: number = 0b10; // 2 in decimal let octal: number = 0o755; // 493 in decimal
Section 3.9: String
let singleQuotes: string = 'single'; let doubleQuotes: string = "double"; let templateString: string = I am ${ singleQuotes }; // I am single
Section 3.10: Array
let threePigs: number[] = [1, 2, 3]; let genericStringArray: Array
Section 3.11: Enum
enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }; let bestDay: Day = Day.Saturday;
enum TenPlus { Ten = 10, Eleven, Twelve }
enum MyOddSet { Three = 3, Five = 5, Seven = 7, Nine = 9 }
Section 3.12: Any
let anything: any = 'I am a string'; anything = 5; // but now I am the number 5
Section 3.13: Void
function log(): void { console.log('I return nothing'); }