有时候TypeScript 无法获取具体的类型信息,这个我们需要使用类型断言(Type Assertions)。
比如我们通过 document.getElementById,TypeScript 只知道函数会返回HTMLElement, 但并不知道它具体的类型:
类型断言就是相对把一个普遍的类型,转成一个相对具体点的类型
案例1:
//类型断言就是相对把一个普遍的类型,转成一个相对具体点的类型
const el =document.getElementById("jiang") as HTMLImageElement
el.src="url地址"
案例2: Person 是Student 的父类
class Person{
}
// 这里现在有一个studernt 继承 Person
class Student extends Person{
studying(){
}
}
function sayHello(p:Person){
(p as Student).studying()
}
const stu=new Student()
sayHello(stu)