介绍
有时候你会遇到这样的情况,你会比TypeScript更了解某个值的详细信息。 通常这会发生在你清楚地知道一个实体具有比它现有类型更确切的类型。
通过类型断言这种方式可以告诉编译器,“相信我,我知道自己在干什么”。 类型断言好比其它语言里的类型转换,但是不进行特殊的数据检查和解构。 它没有运行时的影响,只是在编译阶段起作用。 TypeScript会假设你,程序员,已经进行了必须的检查。
类型断言有两种形式。 其一是“尖括号”语法:
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
另一个为as语法:
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
例子
const nums = [10, 11, 12, 13]
const res = nums.find(i => i>0)
/* 我们可以确定res肯定为number类型,但是ts不知道,它会推断为number或者undefined类型,它认为res可能找
不到 */
// const square = res * res // 提示错误
// 类型断言:明确告诉ts这是某类型
// 方法1:as --> 推荐用法
const num1 = res as number
// 方法2:<> --> jsx下不能用,和标签冲突
// const num1 = <number>res
const square = num1 * num1
网友评论