如何从接口联合中过滤属性值

时间:2019-03-31 12:25:08

标签: reactjs typescript interface autocomplete union

我正在尝试使用(导入)联合类型的道具并将其用于react组件,以便最终app的最终消费者可以在自动建议中“过滤”它们  并验证。

类型:

export type Clothes =
  | Shirt
  | Dress
  | Pants

export interface Shirt {
  size: "M" | "S";
  name: "Shirt";
}

export interface Dress {
  size: "XS";
  name: "Dress";
}

export interface Pants {
  size: "L" | "M" | "S";
  name: "Pants";
}

反应成分:

export const Clothe = (props: Clothes & {className?: string}) => {
    return (
      <div className={props.className}>
        <span>{`${props.name} ${props.size}`}</span>
      </div>     
    )
}

消费者应用:

<Clothe name="Shirt" size="L" /> // this should be invalid

Clothe的大小应仅由MS组成,但结合会给我所有尺寸供选择(L,{{ 1}},MS

例如如果我选择了错误的XSsize道具组合,则应该抛出“ ts”错误。

自动补全功能还应过滤掉特定类型的name道具  基于选择的size道具(最好是反转-对于name道具仅过滤所有具有该大小的size)。

如何实现?

fiddle

0 个答案:

没有答案