Typescript Basic

variable type

  • Typescript 支援 string, boolean, number, array, enum, any, void 等 types

var vs let

  • var 是全區的變數而 let只會在當前的 block scope 有用
"use strict";

function scopeTest(){    
    if(true){
        var foo = "hello";
        var bar = "world";        
    }    
    console.log(foo) // works!!
    console.log(bar) // error!!    
}

Enum

"use strict";

enum Category { Book, CD, Computer} // 0, 1, 2
enum Category { Book = 1, CD, Computer } // 1, 2, 3
enum Category { Book = 5, CD = 8, Computer = 2 } // 5, 8, 2

let myCategory: Category = Category.Book;
console.log(myCategory) // 5

let myCategoryString: string = Category[myCategory] // Book

Array

"use strict";

let str1Array: string[] = ["hello", "world", "hi"];
let str2Array: Array<string> = ["hello", "world", "hi"];
let array3: any[] = [23, true, "hello"];

Tuple

"use strict";

let myTuple: [number, string] = [25, "hello"];
myTuple[0] = 26;
myTuple[1] = "world";