联合类型的接口等效项

时间:2018-04-24 00:47:17

标签: typescript

我有一个Typescript类型定义为:

export type IStepFunctionOperand =
  | IStepFunctionOperand_StringEquals
  | IStepFunctionOperand_StringGreaterThan
  | IStepFunctionOperand_StringGreaterThanEquals
  | IStepFunctionOperand_StringLessThan
  | IStepFunctionOperand_StringLessThanEquals
  | IStepFunctionOperand_NumericEquals
  | IStepFunctionOperand_NumericGreaterThan
  | IStepFunctionOperand_NumericGreaterThanEquals
  | IStepFunctionOperand_NumericLessThan
  | IStepFunctionOperand_NumericLessThanEquals;

每个条件看起来如下所示:

export interface IStepFunctionOperand_NumericLessThanEquals
  extends IStepFunctionBaseLogicalOperand {
  /** compare the value passed in -- and scoped by "Variable" -- to be numerically equal to a stated number */
  NumericLessThanEquals?: number;
}

export interface IStepFunctionBaseLogicalOperand {
  /** points to the specific area of context which is being evaluated in the choice */
  Variable: string;
}

这就是我想要的类型,但将类型制作成接口会非常方便。如果我能够做到这一点,我可以定义一个这样的界面:

export interface IStepFunctionChoiceItem<T> extends Partial<IStepFunctionOperand> {
  // simple operands leverage inheritance but are optional

  // complex operators
  And?: IStepFunctionOperand[];
  Or?: IStepFunctionOperand[];
  Not?: IStepFunctionOperand;

  // State machine
  Next?: keyof T;
  End?: true;
}

这可能吗?

1 个答案:

答案 0 :(得分:1)

虽然您不能使用接口来表示联合,例如从其扩展,但您可以使用类型别名的交集类型来重用或参数化联合类型

从你的例子:

export type StepFunctionChoiceItem<T> =
  & Partial<StepFunctionOperand>
  & {
  // simple operands leverage inheritance but are optional

  // complex operators
  and?: StepFunctionOperand[];
  or?: StepFunctionOperand[];
  not?: StepFunctionOperand;

  // State machine
  next?: keyof T;
  end?: true;
};

export type StepFunctionOperand =
  | StepFunctionOperand_StringEquals
  | StepFunctionOperand_StringGreaterThan
  | StepFunctionOperand_StringGreaterThanEquals
  | StepFunctionOperand_StringLessThan
  | StepFunctionOperand_StringLessThanEquals
  | StepFunctionOperand_NumericEquals
  | StepFunctionOperand_NumericGreaterThan
  | StepFunctionOperand_NumericGreaterThanEquals
  | StepFunctionOperand_NumericLessThan
  | StepFunctionOperand_NumericLessThanEquals;

这与接口扩展不同,因为除了其他差异之外,成员还有。匹配的名称既不会被覆盖也不会被重载,而是自身相交。但是,交集类型将为您提供基本上所需的行为。