TypeScript01:类型断言

41 阅读1分钟

Type Assertion 类型断言

类型断言可以让开发者明确告诉编译器变量的类型,常用于无法推断的情况。

可以使用 as 或尖括号语法。

//“尖括号"语法
let someValuel: any = "this is string";
let strLength1: number = (<string>someValue1).length;

//as语法
let someValue2: any = "this is string";
let strLength2: number = (someValue2 as string).length;

Non-null Assertion 非空断言

非空断言明确告诉 TypeScript 某个值一定不是 null 或 undefined,跳过严格的空值检查

let someValue: any = "this is a string";
const strLength: number = someValue!.length;

const el = document.getElementById("app")!;