4、类型断言
类型断言(Type Assertion)可以用来手动指定一个值的类型。
类型断言
const box = document.querySelector('.box')
// <类型>数据
console.log((<HTMLDivElement>box).innerHTML)
// 值 as 类型
console.log((box as HTMLDivElement).innerHTML)
在 tsx 语法(React 的 jsx 语法的 ts 版)中必须用后一种,及
值 as 类型。
用于创建对象
interface Shape {
    color: string;
    penWidth: number;
    sideLength: number;
}
let square = <Shape>{};
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;
非空断言 --- !
忽略有可能出现的 undefined 和 null 类型
<script lang="ts" setup>
import {  onMounted,ref } from 'vue'
const items = ref<HTMLInputElement[]>()
onMounted(() => {
    console.log(items.value![1]);
})
</script>
<template>
    <div>
       <div v-for="item in 10" :key="item" ref="items">
           {{ item }}
    </div>
    </div>
</template>
不加非空断言 !,或出现下面的提示:

 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号