新元福 發表於 2019-7-1 08:37:00

Typescript - 类型断言

<h2>原文:TypeScript基本知识点整理</h2>
<p>&nbsp;</p>
<h2>零、序言</h2>
<p><span style="font-size: 16px">  类型断言,可以用来手动指定一个值的类型。</span></p>
<p><span style="font-size: 16px">  给我的感觉,和 java 中的强制类型转换很像。<br></span></p>
<p><span style="font-size: 16px">  常常和联合类型配合使用,如:</span></p>
<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;">// 错误示例
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'

// 使用类型断言示例
function f14(name : string, age : string | number) {
    if ((&lt;string&gt;age).length) {//断言
      console.log((&lt;string&gt;age).length)//断言
    }else {
      console.log(age.toString)
    }

}
f14('ljy', 21)
</pre>
</div>
<p>&nbsp;</p>
<h2>注意事项:</h2>
<p><span style="font-size: 16px">  类型断言并不是普通意义上的类型转换,断言成一个联合类型中不存在的类型是不允许的:</span></p>
<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;">function toBoolean(something: string | number): boolean {
    return &lt;boolean&gt;something;
}
// Type 'string | number' cannot be converted to type 'boolean'
</pre>
</div>
<p>&nbsp;</p><br><br>
来源:https://www.cnblogs.com/cc-freiheit/p/11051992.html
頁: [1]
查看完整版本: Typescript - 类型断言