一. TypeScript类型补充
1. 类型断言
有时候TypeScript无法获取具体的类型信息,这个我们需要使用类型断言(Type Assertions) ,TypeScript只允许类型断言转换为 更具体 或者 不太具体 的类型版本,此规则可防止不可能的强制转换。
符号:as
// 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)
2. 非空断言
我们确定传入的参数是有值的,这个时候我们可以使用非空类型断言。非空断言使用的是 ! ,表示可以确定某个标识符是有值的,跳过ts在编译阶段对它的检测
符号:!
// message? -> undefined | string function printMessageLength(message?: string) { // if (message) { // console.log(message.length) // } // vue3源码中很多这种写法 console.log(message!.length) } printMessageLength("aaaa") printMessageLength("hello world")
3. 可选链
可选链事实上并不是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)