1:any类型
任何类型都可以是any类型,any类型就相当于是免检标签,给了开发者很大的自由,typescript允许any类型的值进行任何操作,对它一路绿灯。
let score: any = 666.66;
let num = Math.round(score); // ok
2:unknown类型
任何类型也都可以是unknown类型,但与any完全相反,unknown类型就像是typescript给打上了一个重点检查的标签。在没有对它进行类型检查之前,ubnknow类型的变量是不能进行任何操作的。
let score: unknown = 666.66;
let num = Math.round(score);
3:那如何使unknown类型能正常使用呢?
1.很简单,先进行类型判断
let score: unknown = 666.66;
if(typeof score === "number") {
let num = Math.round(score); // ok
}
2.断言
let score: unknown = 666.66;
let num = Math.round(score as number);
# 或
let num = Math.Round(<number>score);
区别:
- any 会绕过类型检查,直接可用,而 unkonwn 则必须要在判断完它是什么类型之后才能继续用