2、typescript - 类型断言, EventTarget Event
<p>有时候你会遇到这样的情况,你会比TypeScript更了解某个值的详细信息。 通常这会发生在你清楚地知道一个实体具有比它现有类型更确切的类型。</p><p>通过<em>类型断言</em>这种方式可以告诉编译器,“相信我,我知道自己在干什么”。 类型断言好比其它语言里的类型转换,但是不进行特殊的数据检查和解构。 它没有运行时的影响,只是在编译阶段起作用。 TypeScript会假设你,程序员,已经进行了必须的检查。</p>
<p>类型断言有两种形式。 </p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">类型断言有两种形式。 其一是“尖括号”语法:</span>
let someValue: any = "this is a string"<span style="color: rgba(0, 0, 0, 1)">;
let strLength: number </span>= (<string><span style="color: rgba(0, 0, 0, 1)">someValue).length;
</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">另一个为as语法:</span>
let someValue: any = "this is a string"<span style="color: rgba(0, 0, 0, 1)">;
let strLength: number </span>= (someValue as string).length;<br><br><span style="color: rgba(0, 128, 0, 1)">//这块是鼠标的经过事件typescript写法,因为这个onMouseOver是写到tsx里面的,所以这个方法的参数返回的是React.MouseEvent</span><br>onMouseOver = (e:React.MouseEvent) => {<br><span style="color: rgba(0, 128, 0, 1)">//as HTMLElement是把目标target断言为HTMLElement, 预言为肯定不为null或者undefined的情况</span><br> const $target = e.target as HTMLElement; <br> const ref:string = $target.getAttribute('ref) as string;<br>console.log(ref)<br>}<br><br><br><br></pre>
</div>
<p>源: https://www.tslang.cn/docs/handbook/classes.html</p><br><br>
来源:https://www.cnblogs.com/hellolol/p/10895037.html
頁:
[1]