类型断言
帮助进行推断类型
const person = {};person.age = 1;// 类型“{}”上不存在属性“age”。ts(2339)/*****************/interface Person {age: number;}const person = {} as Person;person.age = 1;
双重断言
interface Person {age: number;}const person1 = 'stone' as Person;// 类型 "string" 到类型 "Person" 的转换可能是错误的,因为两种类型不能充分重叠。如果这是有意的,请先将表达式转换为 "unknown"。ts(2352)const person2 = 'stone' as unknown as Person;const person3 = 'stone' as any as Person;
类型守卫
在遇到某些条件语句中,会在语句的块级作用域中缩小类型范围,我们称这种行为为类型守卫。类型守卫的作用就是类型范围缩小。常用的类型守卫包括switch、字面量恒等、typeof、instanceof、in 和自定义类型守卫这几种。
