如何为继承Base的TypeScript接口扩展common属性的类型?
解决方案
要给继承自Base的ExtendedOne和ExtendedTwo分别添加不同类型的common.anotherProp,可以通过以下两种方式实现:
方式一:重写接口的common属性(保留接口定义)
直接在扩展接口中重写common属性,结合交叉类型合并原有属性与新属性:
interface Base { common: { foo: string; }; } interface ExtendedOne extends Base { count: number; // 合并Base的common类型与boolean类型的anotherProp common: Base['common'] & { anotherProp: boolean; }; } interface ExtendedTwo extends Base { origin: string; // 合并Base的common类型与number类型的anotherProp common: Base['common'] & { anotherProp: number; }; }
这种方法既保留了接口的语法特性,又能精准扩展不同类型的属性,TypeScript会自动校验属性兼容性。
方式二:使用类型别名实现灵活组合
如果不需要接口的声明合并特性,用类型别名结合交叉类型会更简洁:
type Base = { common: { foo: string; }; }; type ExtendedOne = Base & { count: number; common: Base['common'] & { anotherProp: boolean; }; }; type ExtendedTwo = Base & { origin: string; common: Base['common'] & { anotherProp: number; }; };
验证示例
两种方式都可以正常通过以下测试代码:
// 符合ExtendedOne类型要求 const exampleOne: ExtendedOne = { count: 5, common: { foo: "hello", anotherProp: false } }; // 符合ExtendedTwo类型要求 const exampleTwo: ExtendedTwo = { origin: "local", common: { foo: "world", anotherProp: 100 } };
内容的提问来源于stack exchange,提问作者four-eyes
相关产品推荐
相关产品推荐

