Typescript 断言
彩蛋:
!.
是什么运算符?
1,类型断言
typescript 允许覆盖它的推断,也就是可以手动指定一个值的类型。换句话说,告诉编译器你比它更了解这个类型,别再报错了。
注意:类型断言只是【欺骗】了编译器,如果代码逻辑有问题,运行时依旧会报错。
1.1,语法
只有2种,
变量名 as 类型
(常用)<类型>值
(很少用)
1.2,用途
1,将一个联合类型断言为其中一个类型
当 TypeScript 不确定一个联合类型的变量到底是哪个类型的时,则只能访问联合类型中的公共属性或方法:
interface Cat {
name: string;
run(): void;
}
interface Fish {
name: string;
swim(): void;
}
function getName(animal: Cat | Fish) {
// 公共属性,ok
return animal.name;
}
function isFish(animal: Cat | Fish) {
// 非公共属性报错,Property 'swim' does not exist on type 'Cat | Fish'.ts(2339)
if (typeof animal.swim === 'function') {
return true;
}
return false;
}
当断言为 fish 时,就不会报错了
function isFish(animal: Cat | Fish) {
if (typeof (animal as Fish).swim === 'function') {
return true;
}
return false;
}
2,编译器无法推断出类型
获取事件对象时,我们可以确定event.target
是一个 html
元素,可 typescript 识别不到。所以需要断言。
const handleMouseDown = (event: MouseEvent) => {
const tagName = (event.target as HTMLElement).tagName
// ...
}
3,断言为 any
一般情况下,我们都尽量避免使用 any
,因为可能会掩盖真正的类型错误。所以只有在非常确定时,再去使用any
。
将一个变量断言为 any 可以说是解决 TypeScript 中类型问题的最后一个手段。
总之,也不能视 any
为洪水猛兽,Typescript 的设计理念之一:在类型的严格性和开发的便利性之间掌握平衡
举例:
当在html
文件中引入一个第三方js
时,通常会给window
对象加属性。但在ts
文件中使用window.xx
时会报错:
// 报错:Property 'foo' does not exist on type 'Window & typeof globalThis'.ts(2339)
window.foo = 1;
此时可以断言为 any
(当然也可以在全局声明文件中,进行声明)
(window as any).foo = 1;
2,非空断言
2.1,语法
使用变量时在变量名后加 !
——变量名!
,这里的 !
是非空断言符号。
彩蛋解密:
!.
是非空断言对象后获取属性,并不是什么运算符。
2.1,用途
明确知道指定值不是undefined
或 null
,可以用非空断言。
举例1:
function fun(value: string | undefined | null) {
// 报错:不能将类型“string | null | undefined”分配给类型“string”。ts(2322)
const str: string = value
const str1: string = value! //ok
// 报错:对象可能为 "null" 或“未定义”。ts(2533)
const length: number = value.length
const length1: number = value!.length //ok
}
举例2:
在Vue3
中,使用ref
定义变量没有默认值。但当使用时明确知道已经被赋值了。
<template>
<Child ref="child" />
<button @click="onClick">点击试下</button>
</template>
<script setup lang="ts">
import Child from './Child.vue'
const child= ref<InstanceType<typeof Child>>()
const onClick = () => {
// 报错,'child.value' is possibly 'null'.ts(18047)
console.log(child.value.count)
// 非空断言可解决
console.log(child.value!.count)
}
</script>
3,确定赋值断言
3.1,语法
声明变量时在变量名后加 !
——变量名!: 类型
,这里的 !:
是确定赋值断言符号。
3.2,用途
以下面的代码为例:
let name!: string
上述表达式就是对编译器说:属性 name
的类型为 string | undefined
。它的值以 undefined
开始。但每次使用name
时,都希望将其视为string
类型。
换句话说,在使用name
时明确知道它已经被赋值了,此时类型是string
举例:
let count: number;
let name!: string;
init();
// 报错:在赋值前使用了变量“count”。ts(2454)
console.log(count);
// ok
console.log(name);
function init() {
count = 10;
name = '求关注'
}
以上。