【发布时间】:2021-12-24 12:17:24
【问题描述】:
我想创建一个类似<alert id="component" /> 的 React 警报组件,还有一个我想从"info", "success", "warning", "error" 中选择一个道具,以便显示不同的消息颜色,该组件类似于<alert id="component" info/> 或@ 987654324@
使用 Typescript,如何使界面在给定的四个选项中只有一个值?
我现在做的是:
type MessageStringType = "info" | "success" | "warning" | "error";
type MessageTypes = {
[K in MessageStringType]: boolean;
};
type oneMessageTypes = Partial<MessageTypes>;
interface Props extends oneMessageTypes {
id: string;
}
但是这个允许来自"info", "success", "warning", "error" 的空值,我怎样才能使类型检查至少需要一个值?
就像:
<Component id="abc" info /> //correct
<Component id="abc" success /> //correct
<Component id="abc" /> //wrong
<Component id="abc" info success /> //wrong
【问题讨论】:
-
为什么不能直接说
interface Props { id: MessageStringType; } -
不...组件设计不像
{ messageType: one of messageType value},他们更喜欢直接使用info、success作为道具而不是messageType -
虽然,我明白你想要什么,它只是看起来不错(老实说,道具类型 def 会令人费解)。除了装饰目的之外,这对用户来说是困难的。更好的设计,IMO,应该是
<Component variant={"info" | "success" | ...} />,因为用户可以这样做:<Component variant={isSuccess ? "success" : "error"} .../>。
标签: reactjs typescript