类型断言as
有时候TypeScript无法获取具体的类型信息,这个我们需要使用类型断言(Type Assertions)。
比如我们通过 document.getElementById,TypeScript只知道该函数会返回 HTMLElement ,但并不知道它 具体的类型
TypeScript只允许类型断言转换为 更具体 或者 不太具体 的类型版本,此规则可防止不可能的强制转换:
// 1.类型断言 as
const el = document.getElementById("why") as HTMLImageElement
el.src = "url地址"
// 2.另外案例: Person是Student的父类
class Person {
}
class Student extends Person {
studying() {
}
}
function sayHello(p: Person) {
(p as Student).studying()
}
const stu = new Student()
sayHello(stu)
// 3.了解: as any/unknown
const message = "Hello World"
// const num: number = (message as unknown) as number
非空类型断言!
当我们编写下面的代码时,在执行ts的编译阶段会报错:
这是因为传入的message有可能是为undefined的,这个时候是不能执行方法的;
但是,我们确定传入的参数是有值的,这个时候我们可以使用非空类型断言:
非空断言使用的是 ! ,表示可以确定某个标识符是有值的,跳过ts在编译阶段对它的检测;
function printMessageLength(message?: string) {
// if (message) {
// console.log(message.length)
// }
// vue3源码
console.log(message!.length)
}
printMessageLength("aaaa")
printMessageLength("hello world")
可选链的使用
可选链事实上并不是TypeScript独有的特性,它是ES11(ES2020)中增加的特性:
可选链使用可选链操作符 ?.;
它的作用是当对象的属性不存在时,会短路,直接返回undefined,如果存在,那么才会继续执行;
虽然可选链操作是ECMAScript提出的特性,但是和TypeScript一起使用更版本;
type Person = {
name: string
friend?: {
name: string
age?: number,
girlFriend?: {
name: string
}
}
}
const info: Person = {
name: "why",
friend: {
name: "kobe",
girlFriend: {
name: "lily"
}
}
}
// 另外一个文件中
console.log(info.name)
// console.log(info.friend!.name)
console.log(info.friend?.name)
console.log(info.friend?.age)
console.log(info.friend?.girlFriend?.name)
// if (info.friend) {
// console.log(info.friend.name)
// if (info.friend.age) {
// console.log(info.friend.age)
// }
// }
??和!!的作用
有时候我们还会看到 !! 和 ?? 操作符,这些都是做什么的呢?
!!操作符:
将一个其他类型转换成boolean类型;
类似于Boolean(变量)的方式;
??操作符:
它是ES11增加的新特性;
空值合并操作符(??)是一个逻辑操作符,当操作符的左侧是 null 或者 undefined 时,返回其右侧操作数,
否则返回左侧操作数;
const message = "Hello World"
// const flag = Boolean(message)
// console.log(flag)
const flag = !!message
console.log(flag)
携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第41天,点击查看活动详情