什么是类型断言?
TypeScript 允许你覆盖它的推断,并且能以你任何你想要的方式分析它,这种机制被称为「类型断言」。 TypeScript 类型断言用来告诉编译器你比它更了解这个类型,并且它不应该再发出错误。
如何使用类型断言?
TypeScript提供了两种语法:
-
as
语法(推荐)typescriptlet someValue: unknown = "this is a string"; let strLength: number = (someValue as string).length;
-
尖括号语法
类似于那些静态语言的类型转换
ini
```typescript
let someValue: unknown = "this is a string";
let strLength: number = (<string>someValue).length;
```
高级断言技巧
-
非空断言操作符(
!
)当你非常确定一个值不是
null
或undefined
时,可以在变量或表达式后使用!
。typescriptfunction process(user: User | null) { // 编译器会报错,因为 user 可能为 null // console.log(user.name); // 我确信在调用这个函数时,user 绝不为 null console.log(user!.name); }
警告: 这是在手动关闭TypeScript的一个重要安全检查。请仅在你100%确定该值非空的情况下使用,否则它会隐藏潜在的
null
引用错误,直到运行时才爆发。 -
const
断言 (as const
)这是一个非常强大的工具,用于告诉TypeScript将一个表达式推断为最具体、最不可变的类型。
- 对于字面量 :类型将是字面量本身,而不是通用的
string
或number
。 - 对于对象 :所有属性都会变成
readonly
。 - 对于数组 :会变成
readonly
元组(tuple)。
typescript// 没有 as const let config = { url: '/api/data', method: 'GET' }; // config 类型: { url: string; method: string; } // 使用 as const let constConfig = { url: '/api/data', method: 'GET' } as const; // constConfig 类型: { readonly url: "/api/data"; readonly method: "GET"; } // 对于数组 let permissions = ['read', 'write']; // permissions 类型: string[] let constPermissions = ['read', 'write'] as const; // constPermissions 类型: readonly ["read", "write"]
- 对于字面量 :类型将是字面量本身,而不是通用的
何时避免使用断言?
-
优先使用类型守卫(Type Guards) :
typeof
、instanceof
、in
操作符或自定义的is
谓词函数是更安全的选择,因为它们会在运行时进行检查,并在此基础上智能地收窄类型。typescript// 不推荐的方式 function printLength(value: string | string[]) { if ((value as string).length) { // 危险的断言 console.log((value as string).length); } else { console.log((value as string[]).length); } } // 推荐的方式:使用类型守卫 function printLengthSafe(value: string | string[]) { if (typeof value === 'string') { console.log(value.length); // value 在这里是 string 类型 } else { console.log(value.length); // value 在这里是 string[] 类型 } }
-
避免
as any
:as any
是最后的手段,它会完全关闭对该变量的类型检查。
总结
如果你喜欢本教程,记得点赞+收藏!关注我获取更多JavaScript/TypeScript开发干货