You need to enable JavaScript to run this app. Typescript如何移除数组item联合类型中的空接口并实现类型安全筛选
优惠活动
大模型
产品
解决方案
定价
更多

Typescript如何移除数组item联合类型中的空接口并实现类型安全筛选

现有不可修改的自动生成TypeScript类型
interface EmptyObject {}

interface TypeA {
  type: 'A';
}

interface TypeB {
  type: 'B';
}

type ItemType = EmptyObject | TypeA | TypeB;

type IArray = (ItemType | null)[] | undefined;
需求实现方案

1. 移除IArray中EmptyObject的工具类型

可以通过条件类型推断提取数组元素,再排除不需要的类型,工具类型实现如下:

type CleanIArray = IArray extends undefined
  ? undefined
  : Exclude<NonNullable<IArray[number]>, EmptyObject>[]

推导后CleanIArray的实际类型为(TypeA | TypeB)[] | undefined,完全满足移除空接口的需求。

2. 通用getItems函数实现

借助TS的类型守卫能力实现,无需类型断言,TS可自动推导返回值类型:

function getItems<T extends ItemType>(
  array: IArray,
  typeGuard: (item: ItemType | null) => item is T
): T[] {
  // 处理数组为undefined的边界情况
  if (!array) return []
  // 直接通过类型守卫过滤,TS自动识别返回值类型
  return array.filter((item): item is T => item !== null && typeGuard(item))
}

如需返回仅包含TypeA或TypeB的数组,只需传入对应类型守卫即可:

// 定义TypeA | TypeB的类型守卫
const isTypeAOrB = (item: ItemType | null): item is TypeA | TypeB => {
  return 'type' in item
}

const listOfTypeAorTypeB = getItems(array, isTypeAOrB)
// 自动推导类型为:(TypeA | TypeB)[]

3. 仅返回TypeA类型元素的实现

无需修改getItems函数,仅需新增对应的类型守卫传入即可:

// 定义仅匹配TypeA的类型守卫
const isTypeA = (item: ItemType | null): item is TypeA => {
  return 'type' in item && item.type === 'A'
}

const listOfTypeA = getItems(array, isTypeA)
// 自动推导类型为:TypeA[]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:57:02