Trying to make presence of at least one optional parameter required, but its presence excludes the others

时间:2019-04-23 15:15:55

标签: javascript typescript types

so let me dive into an example:

type NodeOrMethod<T> =
    | {
          node?: Array<Filter<T>>;
          method: Condition<T>;
      }
    | {
          node: Array<Filter<T>>;
          method?: Condition<T>;
      };

interface BaseFilter {
    label: string;
    value?: string;
}

export type Filter<T> = BaseFilter & NodeOrMethod<T>;

Basically what I want to do is make it so the dev has to either include node or method - which this currently works; however, I want to take it a step further and say IF one of these is present the other CANNOT be. So if they try to include both node and method in the same object it would complain. Has anyone done something like this before?

2 个答案:

答案 0 :(得分:2)

我可能会使用标记的联合(请参见docs的相关部分)来完成您要尝试的操作,例如

list(numbers) 

Example

答案 1 :(得分:0)

Node / JS原理并非真的如此。对象被授予在对象上拥有所需对象的权限,使用代码只关注对象所关心的内容。处理此问题的一些方法包括:

  • 使用工厂方法来确保对象的正确实例化
  • 具有“ type”属性,用于指示是查看节点还是方法

都一样,该类型可疑地被重载了两种含义。我希望有另一种模式可以避免这种情况。如果您陷入了不是您自己的代码的困境,那么上述方法之一应该可以正常工作。