如何为TypeScript联合类型IStepFunctionOperand定义等效接口?
如何将TypeScript联合类型转换为等效接口?
嘿,我来帮你搞定这个问题!你手里的IStepFunctionOperand是个由多个操作数子类型组成的联合类型,想要转成等效的接口对吧?其实核心思路就是把联合类型里每个子类型的键都整合到一个接口里,用可选属性来对应原来的“二选一”逻辑。
先回顾下你给出的联合类型:
export type IStepFunctionOperand = | IStepFunctionOperand_StringEquals | IStepFunctionOperand_StringGreaterThan | IStepFunctionOperand_StringGreaterThanEquals | IStepFunctionOperand_StringLessThan | IStepFunctionOperand_StringLessThanEquals | IStepFunctionOperand_NumericEquals | IStepFunctionOperand_NumericGreaterThan | IStepFunctionOperand_NumericGreaterThanEquals | IStepFunctionOperand_NumericLessThan | IStepFunctionOperand_NumericLessThanEquals;
假设你的每个子类型都是单键对象(比如IStepFunctionOperand_StringEquals是{ StringEquals: string },IStepFunctionOperand_NumericEquals是{ NumericEquals: number }这类结构),那等效的接口可以这么写:
export interface IStepFunctionOperandInterface { // 字符串比较操作符 StringEquals?: string; StringGreaterThan?: string; StringGreaterThanEquals?: string; StringLessThan?: string; StringLessThanEquals?: string; // 数值比较操作符 NumericEquals?: number; NumericGreaterThan?: number; NumericGreaterThanEquals?: number; NumericLessThan?: number; NumericLessThanEquals?: number; }
为什么这是等效的?
原来的联合类型要求必须且只能存在其中一个操作符键,而上面的接口通过把所有键设为可选,覆盖了联合类型的所有可能取值场景。如果想要严格约束“只能有一个键存在”,可以结合类型工具进一步强化(不过这就变成类型而非纯接口了):
// 严格版:确保对象只有一个操作符键 type StrictIStepFunctionOperand = { [K in keyof IStepFunctionOperandInterface]: { [P in K]: IStepFunctionOperandInterface[P] } & { [P in Exclude<keyof IStepFunctionOperandInterface, K>]?: never } }[keyof IStepFunctionOperandInterface];
如果你的子类型有更复杂的结构(比如除了操作符键还有其他公共属性),只需要在接口里把公共属性写为必填,操作符键保持可选就行。
内容的提问来源于stack exchange,提问作者ken
相关产品推荐
相关产品推荐

