TypeScript中的类型断言

类型断言(Type Assertion)是指在编程中显式地指定一个值的类型。在 TypeScript 中,类型断言可以让开发者告诉编译器某个值的确切类型,并且在编译时不进行类型检查或者进行更灵活的类型检查。

下面是一个简单的 TypeScript 类型断言的例子:

// 定义一个变量
let someValue: any = "this is a string";

// 使用类型断言将 someValue 断言为 string 类型
let strLength: number = (someValue as string).length;

// 或者使用尖括号语法
let strLength2: number = (<string>someValue).length;

console.log(strLength); // 输出:16
console.log(strLength2); // 输出:16

在上面的例子中,someValue 被声明为 any 类型,但我们知道它实际上是一个字符串。我们使用了类型断言来告诉 TypeScript 编译器,我们将 someValue 视为字符串类型,并且获取了它的长度。在这里,我们使用了两种类型断言的语法:一种是使用 as 关键字,另一种是使用尖括号(<>)语法。

类型断言在需要处理动态数据或者需要与 JavaScript 交互的情况下非常有用,但需要谨慎使用,因为它绕过了 TypeScript 的类型检查。

 

 

 

*****************************************************

在 TypeScript 中,NonNullable 是一个内置的类型工具,用于从给定的类型中排除 null 和 undefined。它接受一个类型作为参数,并返回一个新的类型,该新类型排除了原始类型中的 null 和 undefined

举个例子:

假设有一个变量 myValue,它的类型可能是 string | null | undefined,也就是说它可以是字符串,也可以是 null 或 undefined。如果我们想要确保 myValue 不是 null 或 undefined,我们可以使用 NonNullable 类型工具来排除这两种可能性。

let myValue: string | null | undefined = "Hello World";

// 使用 NonNullable 类型工具来确保 myValue 不是 null 或 undefined
let nonNullableValue: NonNullable<typeof myValue> = myValue;

// 现在 nonNullableValue 的类型就是 string,而不再包括 null 或 undefined

在这个例子中,NonNullable<typeof myValue> 确保了 nonNullableValue 的类型是 string,因为它排除了 myValue 可能的 null 或 undefined。这样可以帮助开发者在编写类型安全的代码时避免意外处理可能的空值。

posted @ 2024-05-23 22:12  炽橙子  阅读(12)  评论(0编辑  收藏  举报