[TypeScript] 基礎文法

– number, string, boolean, privateがある
– 定数は最初の値を変更できない、変数は変更できる
– varはプルグラム全体、letは宣言された構文の中のみ

let x:number
x = 123
console.log(x)
x = "ok"
console.log(x)

Type ‘string’ is not assignable to type ‘number’. でエラーになる

– let xはlet x:anyと同じでこれであれば型が異なってもOK
– null, undefined, NaNなどの特殊な値も

### 型変換

let x = 123
console.log(x)
let y = "456"
x = +y // x = Number(y)
console.log(x)

テキストを数値にするには、+かNumber()

### 演算

let price = 12500
let withTax = price * 1.1
let woTax = price / 1.1
console.log("price:" + price)
console.log("税別:" + withTax)
console.log("税込" + woTax)

### 制御構文

const num = 12345
const result = num % 2
if (result == 0){ 
    console.log(num + ":偶数")
} else {
    console.log(num + ":奇数")
}

== は等しい、===は型も等しい

const month = 7

if(month <= 0)
    console.log("不明")
else if(month < 3)
    console.log(month + ":冬")
else if(month < 6)
    console.log(month + ":春")
else if(month < 9)
    console.log(month + ":夏")
else if(month < 12)
    console.log(month + ":秋")
else if(month < 13)
    console.log(month + ":冬")
else
    console.log("不明")


三項演算子

const num = 12345

const result = num % 2 === 0 ? '偶数' : '奇数'
console.log(num + ' is ' + result)

switch

const month = 7

switch(month) {
    case 1: console.log(month + " winter"); break
    case 2: console.log(month + " winter"); break
    case 3: console.log(month + " spring"); break
    case 4: console.log(month + " spring"); break
    case 5: console.log(month + " spring"); break
    case 6: console.log(month + " summer"); break
    case 7: console.log(month + " summer"); break
    case 8: console.log(month + " summer"); break
    case 10: console.log(month + " fall"); break
    case 11: console.log(month + " fall"); break
    case 12: console.log(month + " winter"); break
    default: console.log("不明")
}

do while

const max = 100
let total = 0
let count = 0

while(count <= max) {
    total += count++
}
console.log(max + " sum is " + total)

for

const max = 100
let total = 0

for(let i = 1; i <= max; i++){
    total += i
}
console.log("total is " + total)

for(let var in value) と for(let var of value) がある

うむ、ここはどの言語でもだいたい同じ