【问题标题】:Interface equivalent for a union type联合类型的等效接口
【发布时间】:2018-04-24 09:44:02
【问题描述】:

我有一个 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;
}

这可以满足我作为 type 的要求,但是将这个 type 做成 interface 会非常方便。如果我能够做到这一点,我就可以像这样定义一个接口:

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;
}

这可能吗?

【问题讨论】:

  • 这样我就可以使用继承......见上文。
  • 对不起,我看错了。您可以使用交叉点类型。
  • 我对它们很熟悉,但在这里怎么用?
  • export type IStepFunctionChoiceItem&lt;T&gt; = Partial&lt;IStepFunctionOperand&gt; &amp; {Next?: keyof T, members};
  • 有效。如果您愿意,请添加为答案,我会立即将其标记为正确。非常感谢。

标签: typescript


【解决方案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;

这与接口扩展不同,因为除了其他不同之外,成员还具有。匹配的名称既不会被覆盖也不会被重载,而是它们本身是相交的。但是,交叉点类型将为您提供本质上想要的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多