使用 Flow 的互斥属性

Mutually exclusive attributes using Flow

我正在为我工​​作的公司构建一个 UI 组件。它在 React Native 中,并使用 Flow 进行类型检查。事情是我希望组件具有某些变体,但它们迫使我只有 booleans 组件属性。我希望组件禁止使用多个变体。

假设我的组件 <Button> 有两个变体:primarysecondary。如果我可以使用属性 variant,那会更容易,因为我可以使用 variant='primary'。但我不能那样做。它必须是 primary=true 但我必须将其设置为独占:如果我有 primary:true 你不应该被允许在同一个组件中使用 secondary:true

我一直在检查 docs 但我找不到方法。这是有道理的,你为什么要有一个?别再用 boolean 了,对吧?

问题是:有办法吗?

不确定我是否遵循了您要实现的所有魔法,但是这个:

if I have primary:true you shouldn't be allowed to use secondary:true in the same component.

exact object types很容易实现。只需创建 2 个不同的确切对象类型并将组件道具标记为其中之一:

type TPrimary = {|
  primary: boolean,
|};

type TSecondary = {|
  secondary: boolean,
|};

type T = TPrimary | TSecondary;

const C = (props: T) => <div {...props} />

const mounted = <C primary  />;

const mounted2 = <C secondary  />;

// error
const mounted3 = <C primary secondary  />

Try