注意:類型斷言(Type Assertion)可以用來手動指定一個值的類型。
語法:
<類型>值
或
值 as 類型
類型斷言的用法如上,在需要斷言的變量前加上 即可
就上篇文章中TypeScript 不確定一個聯合類型的變量到底是哪個類型的時候來說
function f13(name : string, age : string | number) {
if (age.length) { //報錯
console.log(age.length) //報錯
} else {
console.log(age.toString)
}
}
f13('ljy', 21)//Property 'length' does not exist on type 'string |number'.Property 'length' does not exist on type 'number'
此時可以使用類型斷言,將 age 斷言成 string
function f14(name : string, age : string | number) {
if ((<string>age).length) {//斷言
console.log((<string>age).length)//斷言
} else {
console.log(age.toString)
}
}
f14('ljy', 21)
類型斷言不是類型轉換,斷言成一個聯合類型中不存在的類型是不允許的:
function toBoolean(something: string | number): boolean {
return <boolean>something;
}
Type 'string | number' cannot be converted to type 'boolean'
總結:
到這篇文章之後,Ts的所有基礎知識已經差不多整理完了,後面會帶來node.js的基礎知識文章,因爲工作有時候太忙,不是不寫,是沒時間,哈哈哈。敬請期待哦~
你點的每個贊,我都認真當成了喜歡