概要:在本教程中,您将学习 TypeScript 中的类型断言,它允许您将新的类型分配给值。
类型断言指示 TypeScript 编译器将值视为指定类型。在 TypeScript 中,您可以使用 as 关键字或 <> 运算符进行类型断言。
使用 as 关键字进行类型断言
以下使用 querySelector() 方法选择 HTML 文档中的第一个输入元素
let el = document.querySelector('input["type="text"]');Code language: TypeScript (typescript)由于 document.querySelector() 方法的返回类型为 Element 类型,因此以下代码会导致编译时错误
console.log(el.value);Code language: TypeScript (typescript)错误
Property 'value' does not exist on type 'Element'.Code language: JavaScript (javascript)原因是 value 属性在 Element 类型中不存在。它仅在 HTMLInputElement 类型中存在。
要解决此问题,您可以指示 TypeScript 编译器使用 as 关键字将 el 元素的类型视为 HTMLInputElement,如下所示
const el = document.querySelector('input[type="text"]');
const input = el as HTMLInputElement;Code language: TypeScript (typescript)现在,input 变量具有 HTMLInputElement 类型。因此,访问其 value 属性不会导致任何错误。以下代码有效
console.log(input.value);Code language: TypeScript (typescript)访问属性时,另一种将 HTMLInputElement 类型分配给 Element 对象的方法如下
let enteredText = (el as HTMLInputElement).value;Code language: TypeScript (typescript)请注意,HTMLInputElement 类型 扩展 HTMLElement 类型,而 HTMLElement 类型扩展到 Element 类型。
从 typeA 到 typeB 的变量类型断言的语法如下
let a: typeA;
let b = a as typeB;Code language: TypeScript (typescript)使用 <> 运算符进行类型断言
除了 as 关键字之外,您还可以使用 <> 运算符执行类型断言。例如
let input = <HTMLInputElement>document.querySelector('input[type="text"]');
console.log(input.value);Code language: TypeScript (typescript)使用 <> 运算符进行类型断言的语法如下
let a: typeA;
let b = <typeB>aCode language: TypeScript (typescript)类型断言结果
如果类型断言失败,则根据您如何使用类型断言和实际运行时类型,将发生不同类型的错误。
1) 编译时错误
当您尝试在不兼容的类型之间执行类型断言时,TypeScript 编译器可能会向您发出错误或警告。例如
let price = '9.99';
let netPrice = price as number; // errorCode language: JavaScript (javascript)在此示例中,我们尝试将数字类型分配给字符串,TypeScript 编译器发出以下编译时错误
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.Code language: JavaScript (javascript)2) 运行时错误
当您对对象执行类型断言以使其成为与其结构不匹配的类型,并尝试访问不存在的属性时,您将获得运行时错误。例如
let el = document.querySelector('#name');
let input = el as HTMLInputElement;
console.log(input.value.length);Code language: JavaScript (javascript)在此示例中,如果具有 ID #name 的元素不是输入元素,则 input.value 在运行时将为 undefined。因此,访问 value 的 length 属性会导致运行时错误
TypeError: Cannot read properties of undefined (reading 'length')Code language: JavaScript (javascript)3) 意外行为
如果类型断言不正确,您可能不会收到编译时或运行时错误,但您可能在代码的后面遇到意外行为。这可能会使调试变得具有挑战性,因为错误可能不会在类型断言的地方发生。
概要
- 类型断言允许您将新的类型分配给值。
- 使用
as关键字或<>运算符执行类型断言。