# TypeScript 逻辑控制

# if/else

function f(s: number | string | undefined) {
    if( s === 200){
        console.log("这是数字")
    } else if(s === 'success'){
        console.log("这是字符串")
    } else if(s === undefined) {
        console.log("这是 undefined 类型")
    } else {
        console.log("啥也不是")
    }
}

f(200)
f('success')
f(undefined)

# swicth

function f(s: number | string | undefined) {
    switch(s){
        case 200:
            console.log("这是数字")
            break
        case 'success':
            console.log("这是字符串")
            break
        case undefined:
            console.log("这是 undefined")
            break
        default:
        		console.log("啥也不是")
    }
}
f(200)
f('success')
f(undefined)
f(404)

# for

function f(s: string){
    for(let i=0; i<10; i++){
        console.log(i + s)
    }
}
f('hedon')

# while

function f(s: string){
    let i = 0
    while(i < 10){
        console.log(i + s)
        i ++
    }
}
f('hedon')

# try/catch

let sum = 0

for(let i=0; i < 100; i++){
    try{
        sum+=1
        if(i % 17 === 0){
            throw `bad number ${i}`
        }
    }catch(err){
        console.log(err)
    }
}

console.log(sum)
上次更新: 11/3/2021, 8:49:20 AM