- ts不能直接运行,会编译成js,再运行
- ts = js + 类型定义
- 最好不要用var,用let和const
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类型
- any类型:放弃ts的类型检查,退化成弱类型
- 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)
}
}
枚举
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"