cnzhuanyong 2023-04-20 05:32 采纳率: 36.8%
浏览 22
已结题

如何约束 prop 能传入多个值,但每个值限1次?

type DndBoxProps = React.PropsWithChildren<{
  accepts?: any[];
  // "all" | "left" | "right" | "top" | "bottom"
  // 每个只能填一次,
  // 如果 all 填了, 其他就不能存在
  // 默认值 为 all
  edge?:  string[];
}>;

  • 写回答

1条回答 默认 最新

  • 崽崽的谷雨 2023-04-20 08:51
    关注

    引用自 chatGPT:
    可以使用 TypeScript 中的联合类型和类型别名来实现这个需求。具体做法如下:

    1.定义一个类型别名来描述边缘类型列表,其中包含了所有可能的边缘类型,包括 "all"、"left"、"right"、"top" 和 "bottom":

    type EdgeType = "all" | "left" | "right" | "top" | "bottom";
    
    

    2.定义一个接口类型 DndBoxProps 来约束组件的 props,其中 edge 属性的类型为 EdgeType[]:

    interface DndBoxProps {
      accepts?: any[];
      edge?: EdgeType[];
      children?: React.ReactNode;
    }
    
    

    3.在调用组件的地方,可以像下面这样使用 DndBox 组件,并传入 edge 属性,每个属性只能传入一次,否则会报错。

    import { DndBoxProps } from './DndBoxProps';
    function App() {
      return (
        <div>
          <DndBox accepts={['text']} edge={['all']} />
          <DndBox accepts={['text', 'image']} edge={['left', 'right']} />
          <DndBox accepts={['image']} edge={['top']} />
        </div>
      );
    }
    
    

    这样,在使用 DndBox 组件时,就能够约束 edge 属性只能传入 "all"、"left"、"right"、"top" 和 "bottom" 中的任意一个,每个值只能传入一次。

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 9月10日
  • 修改了问题 4月20日
  • 创建了问题 4月20日