TypeScript日常类型(8): Type Annotations

75 阅读1分钟

类型断言(Type Assertions)

有时候,你对某个值的类型有更多信息,而 TypeScript 无法自行推断。

例如,在使用 document.getElementById 时,TypeScript 只知道它会返回某种 HTMLElement,但你可能确切知道页面上某个特定的 ID 一定是 HTMLCanvasElement。

在这种情况下,你可以使用 类型断言 来指定一个更具体的类型

const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;

类似于类型注解,类型断言 在编译时会被移除,不会影响代码的运行时行为。

你还可以使用 尖括号语法(),它的作用与 as 语法相同,但在 .tsx 文件中不能使用此方式:

const myCanvas = <HTMLCanvasElement>document.getElementById("main_canvas");

注意: 由于类型断言在编译时会被移除,因此它不会在运行时进行类型检查。如果类型断言是错误的,不会抛出异常或返回 null,而是可能导致运行时错误。

TypeScript 仅允许将类型转换为更具体或更宽泛的版本,以防止不可能的强制转换,例如:

const x = "hello" as number; 
// ❌ Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

有时候,这条规则可能过于严格,阻止了一些实际上是有效的复杂转换。如果遇到这种情况,你可以使用两次类型断言:先转换为 any(或 unknown,后面会介绍),然后再转换为目标类型:

const a = expr as any as T;    

这样,TypeScript 允许你进行更灵活的类型转换,但请谨慎使用,以避免潜在的类型安全问题。