如何在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
相关产品推荐
相关产品推荐

