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

如何实现基于actions属性的TypeScript条件类型C?

实现基于actions属性存在性的条件类型C

要实现你需要的条件类型,可通过TypeScript的泛型条件类型来判断传入的类型是否包含actions属性,从而返回对应的A或B类型:

interface A {
  label: string
  prop: string
}

interface B {
  label?: string
  actions: string[]
}

// 泛型条件类型:判断T是否包含actions属性,返回对应类型
type C<T> = T extends { actions: unknown } ? B : A;

// 使用示例:通过typeof让TS自动推断变量类型
const c1: C<typeof c1> = {
  label: 'c1',
  prop: 'c1',
}

const c2: C<typeof c2> = {
  label: 'c2',
  actions: ['c2'],
}

如果想让类型推断更简洁,也可以通过辅助函数实现自动匹配,无需手动传入泛型参数:

// 辅助函数:自动推断传入值的类型并匹配A/B,同时避免非法的交叉属性
function createC<T extends A | (B & { prop?: never })>(value: T): T {
  return value;
}

const c1 = createC({
  label: 'c1',
  prop: 'c1',
}); // 类型自动推断为A

const c2 = createC({
  label: 'c2',
  actions: ['c2'],
}); // 类型自动推断为B

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:02:17