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

如何在TypeScript中混合类与接口创建新类型?

合并类与接口属性创建新类型的方法

当然可以,你可以使用TypeScript的**交叉类型(Intersection Types)**来实现这个需求,交叉类型会自动合并类和接口的所有属性,并且保留readonly修饰符。

实现代码

首先保留你原有的类和接口定义:

export class A {
  constructor(public readonly prop1: string, public readonly prop2: number) {}
}

export interface I {
  readonly numParam: number;
  readonly strParam: string;
}

然后通过&操作符创建交叉类型:

export type AI = A & I;

类型验证

这个AI类型的结构完全符合你的预期,展开后等效于:

type AI = {
  readonly prop1: string;
  readonly prop2: number;
  readonly numParam: number;
  readonly strParam: string;
}

你可以像使用普通类型一样使用AI,比如定义变量:

const obj: AI = {
  prop1: "test",
  prop2: 123,
  numParam: 456,
  strParam: "hello"
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:35:14