TypeScript的类型断言,有点像ABAP的强制类型转换
typescript 类型 ABAP 强制 类型转换 断言
2023-09-14 09:02:44 时间
通过类型断言这种方式可以告诉编译器,“相信我,我知道自己在干什么”。 类型断言好比其它语言里的类型转换,但是不进行特殊的数据检查和解构。 它没有运行时的影响,只是在编译阶段起作用。 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;
两种方式等价,但是在TypeScript里使用JSX时,只有 as语法断言是被允许的。
相关文章
- [Typescript] Use Generics in a Reduce Function
- [Typescript] 90. Medium - Replace
- [Typescript] “Record” Mapped Type
- [Typescript] Creating Chainable Method Abstractions with Generics and the Builder Pattern - 05
- [Typescript] Get All of an Object’s Values
- [Typescript] Zod in actions
- [React Typescript 2022] Type React hooks
- [Typescript] “Partial” Mapped Type
- [TypeScript] Create Explicit and Readable Type Declarations with TypeScript mapped Type Modifiers
- [Vue + TS] Write a Vue Component as a Class in TypeScript
- [TypeScript] Using Gulp with TypeScript
- TypeScript 里 never 类型的用法举例
- TypeScript 函数类型参数的用法举例
- 5种在TypeScript中使用的类型保护
- TypeScript中的递归类型简析
- 实现一个自动生成typescript类型声明的工具