TypeScript高手密技:解密类型断言、非空断言与 `const` 断言

什么是类型断言?

TypeScript 允许你覆盖它的推断,并且能以你任何你想要的方式分析它,这种机制被称为「类型断言」。 TypeScript 类型断言用来告诉编译器你比它更了解这个类型,并且它不应该再发出错误。

如何使用类型断言?

TypeScript提供了两种语法:

  1. as 语法(推荐)

    typescript 复制代码
    let someValue: unknown = "this is a string";
    let strLength: number = (someValue as string).length;
  2. 尖括号语法

类似于那些静态语言的类型转换

ini 复制代码
```typescript
let someValue: unknown = "this is a string";
let strLength: number = (<string>someValue).length;
```

高级断言技巧

  1. 非空断言操作符(!

    当你非常确定一个值不是nullundefined时,可以在变量或表达式后使用!

    typescript 复制代码
    function process(user: User | null) {
      // 编译器会报错,因为 user 可能为 null
      // console.log(user.name);
    
      // 我确信在调用这个函数时,user 绝不为 null
      console.log(user!.name); 
    }

    警告: 这是在手动关闭TypeScript的一个重要安全检查。请仅在你100%确定该值非空的情况下使用,否则它会隐藏潜在的null引用错误,直到运行时才爆发。

  2. const 断言 (as const)

    这是一个非常强大的工具,用于告诉TypeScript将一个表达式推断为最具体、最不可变的类型。

    • 对于字面量 :类型将是字面量本身,而不是通用的stringnumber
    • 对于对象 :所有属性都会变成readonly
    • 对于数组 :会变成readonly元组(tuple)。
    typescript 复制代码
    // 没有 as const
    let config = { url: '/api/data', method: 'GET' };
    // config 类型: { url: string; method: string; }
    
    // 使用 as const
    let constConfig = { url: '/api/data', method: 'GET' } as const;
    // constConfig 类型: { readonly url: "/api/data"; readonly method: "GET"; }
    
    // 对于数组
    let permissions = ['read', 'write'];
    // permissions 类型: string[]
    
    let constPermissions = ['read', 'write'] as const;
    // constPermissions 类型: readonly ["read", "write"]

何时避免使用断言?

  1. 优先使用类型守卫(Type Guards)typeofinstanceofin 操作符或自定义的is谓词函数是更安全的选择,因为它们会在运行时进行检查,并在此基础上智能地收窄类型。

    typescript 复制代码
    // 不推荐的方式
    function printLength(value: string | string[]) {
      if ((value as string).length) { // 危险的断言
        console.log((value as string).length);
      } else {
        console.log((value as string[]).length);
      }
    }
    
    // 推荐的方式:使用类型守卫
    function printLengthSafe(value: string | string[]) {
      if (typeof value === 'string') {
        console.log(value.length); // value 在这里是 string 类型
      } else {
        console.log(value.length); // value 在这里是 string[] 类型
      }
    }
  2. 避免 as anyas any 是最后的手段,它会完全关闭对该变量的类型检查。

总结

如果你喜欢本教程,记得点赞+收藏!关注我获取更多JavaScript/TypeScript开发干货

相关推荐
专注API从业者1 小时前
Python + 淘宝 API 开发:自动化采集商品数据的完整流程
大数据·运维·前端·数据挖掘·自动化
你的人类朋友2 小时前
【Node&Vue】JS是编译型语言还是解释型语言?
javascript·node.js·编程语言
样子20183 小时前
Uniapp 之renderjs解决swiper+多个video卡顿问题
前端·javascript·css·uni-app·html
Nicholas683 小时前
flutterAppBar之SystemUiOverlayStyle源码解析(一)
前端
黑客飓风3 小时前
JavaScript 性能优化实战大纲
前端·javascript·性能优化
emojiwoo5 小时前
【前端基础知识系列六】React 项目基本框架及常见文件夹作用总结(图文版)
前端·react.js·前端框架
张人玉5 小时前
XML 序列化与操作详解笔记
xml·前端·笔记
杨荧5 小时前
基于Python的宠物服务管理系统 Python+Django+Vue.js
大数据·前端·vue.js·爬虫·python·信息可视化
YeeWang6 小时前
🎉 Eficy 让你的 Cherry Studio 直接生成可预览的 React 页面
前端·javascript