两种类型断言语法
尖括号语法
const value: unknown = "TypeScript Rocks!"
// 尖括号语法
const length = (<string>value).length
as语法
const length = (value as string).length
应用场景
处理联合类型
interface Cat { meow(): void; }
interface Dog { bark(): void; }
type Pet = Cat | Dog;
function petSound(pet: Pet) {
if ((pet as Cat).meow) {
(pet as Cat).meow();
} else {
(pet as Dog).bark();
}
}
类型守卫:缩小类型的范围,常用的有typeof、instanceof、in
typeof守卫:处理基本类型
if (typeof value === "string") {
value.toUpperCase()
}
instanceof守卫:适用于类示例判断
class Cat {
meow() {
} }
class Dog {
bark() {
} }
function animalSound(animal: Cat | Dog) {
if (animal instanceof Cat) {
animal.meow();
}
}