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

如何在TypeScript中合并可选属性的类型A与修改后的类型B?

TypeScript 类型AB的实现方案

首先修正一个小细节:TypeScript 中没有int类型,原类型A里的a2: int应该改为a2: number。

要实现需求中的类型AB,可以通过 TypeScript 内置工具类型组合完成:

// 修正后的原类型
interface A {
    a1: string;
    a2: number;
}

interface B {
    b1: number;
}

// 定义类型AB
type AB = Partial<A> & {
    b1: string;
};

原理说明:

  • Partial<A>:将类型A的所有属性转换为可选属性,对应需求中"A的所有可选属性"的要求;
  • { b1: string }:重新定义B类型中b1的类型为string;
  • 交叉类型&:把上述两部分的属性合并,得到最终的AB类型。

验证一下,此时AB类型的结构完全符合需求:

// 符合类型约束的示例
const abInstance: AB = {
    b1: "test"
};

// 也可以包含A的可选属性
const abInstance2: AB = {
    a1: "hello",
    a2: 123,
    b1: "world"
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:20:39