告别 any!用联合类型打造更灵活、更安全的 TS 代码

一、什么是联合类型?

联合类型使用竖线 | 作为分隔符,表示一个值可以是列出的类型中的任意一种。

typescript 复制代码
// ID 只接收数字或字符串作为参数
function printId(id: number | string) {
      console.log("Your ID is: " + id);
}

printId(101);       // OK
printId("202");     // OK
printId({ id: 303 }); // 类型"{ id: number; }"的参数不能赋给类型"string | number"的参数。

二、使用类型守卫收窄类型(断言类型)

1. typeof 类型守卫

typeof 是最常见的类型守卫,一般处理 string, number, boolean, symbol, bigint, undefined, function 这些基础类型时使用。

typescript 复制代码
function printId(id: number | string) {
    if (typeof id === 'string') {
        // 在这个代码块内,TypeScript 知道 id 的类型是 string
        console.log(id.toUpperCase());
    } else {
        // 在这个代码块内,TypeScript 知 id 的类型是 number
        console.log(id);
    }
}

printId('good');
printId(10);

2. instanceof 类型守卫

当处理类的实例时,使用instanceof 判断类型

typescript 复制代码
class User {
  constructor(public name: string) {
    this.name =  name;
   }
}

class Product {
  constructor(public title: string) { 
    this.title = title;
  }
}

function printEntity(entity: User | Product) {
  if (entity instanceof User) {
    // entity 被收窄为 User 类型
    console.log("User: " + entity.name);
  } else {
    // entity 被收窄为 Product 类型
    console.log("Product: " + entity.title);
  }
}

let user = new User('john')
printEntity(user)
let product = new Product('title')
printEntity(product)

3. in 操作符守卫

在判断对象的属性时,常常使用in

typescript 复制代码
interface Fish {
  swim: () => void;
}

interface Bird {
  fly: () => void;
}

function move(animal: Fish | Bird) {
  if ("swim" in animal) {
    // animal 被收窄为 Fish 类型
    return animal.swim();
  }
  // animal 被收窄为 Bird 类型
  return animal.fly();
}

let fish = {
  swim:()=>{
    console.log('fish is swim');
  }
}

let bird = {
  fly:()=>{
    console.log('bird fly');
  }
}

move(fish);
move(bird);

总结

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

相关推荐
FreeBuf_12 分钟前
新型域名前置攻击利用Google Meet、YouTube、Chrome及GCP构建流量隧道
前端·chrome
c0detrend17 分钟前
技术架构设计:如何打造一个高性能的Chrome截图插件
前端·chrome
幽络源小助理22 分钟前
8、幽络源微服务项目实战:前端登录跨域同源策略处理+axios封装+权限的递归查询增删改+鉴权测试
前端·微服务·架构
API开发27 分钟前
apiSQL+GoView:一个API接口开发数据大屏
前端·后端·api·数据可视化·数据大屏·apisql
运维开发王义杰29 分钟前
nodejs:揭秘 npm 脚本参数 -- 的妙用与规范
前端·npm·node.js
我是日安36 分钟前
从零到一打造 Vue3 响应式系统 Day 18 - Reactive:深入 Proxy 的设计思路
前端·vue.js
你的人类朋友37 分钟前
🍃说说Base64
前端·后端·安全
ze_juejin42 分钟前
Node.js 全局变量完整总结
前端
ttyyttemo44 分钟前
Learn-Jetpack-Compose-By-Example---TextFieldValue
前端
_AaronWong44 分钟前
多页面应用登录状态共享:基于弹出窗口的通用解决方案
前端·javascript·vue.js