literal type(类似枚举)

let answer : "yes" | "no" | "maybe" = "maybe"
//不一定是一个类型
let httpCode : 200 | 300 | 400 | 500 | "200" | "500" = 200

answer = "yes"

let s: string = answer

类型的并集

//可以是string还可以是number
let s: string | number = "12"

any类型和undefined类型

try…catch及``的用法

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

}

Untitled

枚举

enum HTTPStatus{
    OK,
    NOT_FOUND,
    INTERNAL_SERVER_ERROR,
}

function p(s: HTTPStatus){
    HTTPStatus.INTERNAL_SERVER_ERROR
}

p(HTTPStatus.INTERNAL_SERVER_ERROR) // 输出2,INTERNAL_SERVER_ERROR的序号

//下面是指定了值,那么console.log会出现对应的值
enum HTTPStatus{
    OK = 200,
    NOT_FOUND = 404,
    INTERNAL_SERVER_ERROR = 500,
}
console.log(HTTPStatus.INTERNAL_SERVER_ERROR) // 500
console.log(HTTPStatus[200]) // OK
enum Timing{
    L = "line",
    O  = "OP"
}

console.log(Timing.L) //"line"

Untitled