type DndBoxProps = React.PropsWithChildren<{
accepts?: any[];
// "all" | "left" | "right" | "top" | "bottom"
// 每个只能填一次,
// 如果 all 填了, 其他就不能存在
// 默认值 为 all
edge?: string[];
}>;
如何约束 prop 能传入多个值,但每个值限1次?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
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" 中的任意一个,每个值只能传入一次。
解决 无用评论 打赏 举报