登录/注册
小开开
2649
占位
2
占位
0
浏览量
占位
粉丝
占位
关注
TypeScript-类型断言
小开开
2020-12-04 17:17:40 2020-12-04
111
0

类型断言

类型断言用来明确告诉编译器一个值的类型,相当于类型转换,断言有两种语法格式:

// 1、尖括号语法
<类型表达式>值
// 2、as语法
值 as 类型表达式

为了避免和 JSX 语法产生冲突,尖括号语法只能在 tsx 文件中使用

let someValue: any = "this is a string";
// 1、尖括号语法
let strLength: number = (<string>someValue).length;
// 2、as语法
let strLength: number = (someValue as string).length;

通过一个典型案例演示类型转换的场景:

class Shape {}
class Circle extends Shape {
showColor() {
return "red";
}
}
// Circle是Shape的子类型,因而可以直接作为Shape类型返回
function createShape(kind: string): Shape {
return new Circle();
}
// circle 被编译器推导为 Shape 类型
var circle = createShape("circle");
// 错误,error TS2339: Property 'showColor' does not exist on type 'Shape'
console.log(circle.showColor());

解决这个问题很简单,只需要对 circle 变量添加类型断言即可,相当于强制类型转换:

// 正确
console.log((<Circle>circle).showColor());

尖括号 <> 的运算符优先级低于点号 . ,因而必须用括号将断言表达式扩起来,直接这样写是错误的:

// 错误,error TS2339: Property 'showColor' does not exist on type 'Shape'
console.log(<Circle>circle.showColor());

在这种情形下,<Circle> 实际上是断言 circle.showColor() 表达式的结果为 Circle 类型

暂无评论