如何为TypeScript接口的部分字段实现动态类型定义?
TypeScript泛型接口的扩展与使用
一、你的泛型接口已满足需求
你定义的BaseInterface<T>本身就是泛型接口,它的设计完全符合你的预期:当传入具体类型SomeOtherInterfaceOrType作为泛型参数时,dynamicA的类型会自动替换为该具体类型。
举个实际例子:
先定义目标类型:
// 示例的具体类型或接口 interface SomeOtherInterface { status: boolean; tags: string[]; }
当你使用BaseInterface<SomeOtherInterface>时,这个类型的结构为:
{ staticA: string; staticB: number; dynamicA: SomeOtherInterface; // 已自动替换为指定类型 }
二、创建该类型的新接口/类型
有两种常用方式生成基于泛型接口的新类型:
1. 使用type别名直接定义
这是最简洁的方式,直接将泛型接口实例化后的结果赋值给类型别名:
type ExtendedType = BaseInterface<SomeOtherInterface>;
之后可像使用普通类型一样使用ExtendedType。
2. 使用interface继承泛型接口
若需要用interface而非type,可通过继承实现:
interface ExtendedInterface extends BaseInterface<SomeOtherInterface> {}
这个ExtendedInterface和上述ExtendedType功能完全一致,包含原接口所有属性,且dynamicA的类型为SomeOtherInterface。
三、实际使用示例
创建上述类型的对象:
const demoObj: ExtendedInterface = { staticA: "test", staticB: 456, dynamicA: { status: true, tags: ["ts", "generic"] } };
内容的提问来源于stack exchange,提问作者Enes Kaplan
相关产品推荐
相关产品推荐

