告别 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开发干货

相关推荐
恋猫de小郭几秒前
Flutter 的文字为什么比 SwiftUI 更细?问题主要在 Skia 的 256 项查找表里
android·前端·flutter
lexiangqicheng3 分钟前
前端高阶面试核心通关指南:深入解析Vue3与React18底层原理及性能优化
前端·面试·性能优化
怕浪猫3 分钟前
前端对接聊天 API:我用 React 做了一个比 ChatGPT 还好看的界面
前端·后端·面试
程序员小孔.7 分钟前
基于 Spring Cloud + Vue 的 JEEWMS 开源仓储管理平台设计与实现
前端·javascript·vue.js·spring boot·spring cloud·开源
IT_陈寒8 分钟前
深入理解Python:核心原理与最佳实践
前端·人工智能·后端
我喜欢就喜欢20 分钟前
Chrome 插件开发实战指南
前端·chrome
夕阳_醉了23 分钟前
花了一天的时间,地板式扫盲了vue3所有API盲点
前端·javascript·vue.js
LinDaiuuj33 分钟前
Figma Specs 高效交付与开发协作指南
前端·figma
风骏时光牛马1 小时前
大模型底层架构与推理机制源码深度剖析
前端
java1234_小锋6 小时前
【技术专题】HTML5 网页技术 - HTML5 Canvas 基础以及动画入门
前端·html·html5