You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组中的Union Type:如何识别类型及修改值

TypeScript 联合类型数组处理方案

问题1:让TypeScript正确推断find返回的Loaded|undefined类型

默认情况下,Array.find()的回调无法被TypeScript自动识别为类型守卫,需要通过类型谓词(type predicate)明确筛选逻辑对应的类型:

type Loading = {
    loading: true
}

type Loaded = {
    loading: false,
    date: string,
    value: number,
}

type Items = Loading | Loaded

const items: Items[] = []

// 定义类型谓词,明确返回true时item为Loaded类型
const isLoaded = (item: Items): item is Loaded => !item.loading

const firstLoaded = items.find(isLoaded) 
console.log(firstLoaded?.date) // 现在能正常访问date属性

通过item is Loaded这个类型谓词,TypeScript可以精准推断find的返回类型为Loaded | undefined,从而支持可选链访问属性。


问题2:将数组中的Loading类型元素转为Loaded类型

首先需要用类型谓词确认找到的元素是Loading类型,修改loading状态后,必须补充Loaded要求的所有必填属性,TypeScript才会认可类型转换:

// 定义Loading类型的类型谓词
const isLoading = (item: Items): item is Loading => item.loading

const firstUnloaded = items.find(isLoading) 
if (firstUnloaded) {
    // 修改loading状态
    firstUnloaded.loading = false
    // 补充Loaded类型的必填属性
    firstUnloaded.date = new Date().toISOString()
    firstUnloaded.value = 100
    // 此时firstUnloaded的类型自动变为Loaded
}

如果需要先强制转换类型(需确保后续补充属性,避免运行时错误),也可以用类型断言:

if (firstUnloaded) {
    firstUnloaded.loading = false
    const loadedItem = firstUnloaded as Loaded
    loadedItem.date = "2024-05-20"
    loadedItem.value = 200
}

内容的提问来源于stack exchange,提问作者qms

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 22:07:54