问题描述
我知道在Dart中没有像这样的字符串文字类型:
I know that in Dart there's no string literal types like:
interface IButtonProps {
readonly variant: 'primary' | 'secondary'
readonly size: 'small' | 'regular' | 'big' | 'a little bigger than usually'
}
const Button:FC<IButtonProps> = ({variant, size}) => {
// ...
}
但是,如果我真的希望该按钮仅接受主要/次要变体,并在编写库时向我/我的团队/社区建议变体,那我会有什么选择呢?
But what are my choises if i really want that button to accept only primary/secondary variants and suggest variants to me/my team/the community if i'm writing a library ?
我知道我可以声明道具,但是在编译时不会有任何建议仅在编辑器中出现.那么,我能做些什么来获得该功能?类似于创建ButtonVariants类并仅接受其字段/创建枚举/列表/设置/任何东西,或者我不知道...
I know i can assert props but there would not be any suggestions in editor only error at compile time.So is there anything i can do to get that functionality ? Something like creating a ButtonVariants class and accepting only its fields / creating enum / list / set / whatever or i dont know...
我真的需要任何形式的严格输入,而不是像PrimaryButton SecondaryButton SmallPrimaryButton这样的小部件创建一个地狱.
I really need that strict typing in any form and not to create one hell of a widgets like PrimaryButton SecondaryButton SmallPrimaryButton...
请注意,这个愚蠢的小学/中学只是一个例子.
Note that this stupid primary/secondary is just an example.
推荐答案
您可以像这样使用枚举器
You can just use enumarators like this
enum ButtonType { primary, secondary }
enum ButtonSize { small, regular, big }
class Button {
final ButtonType type;
final ButtonSize size;
AbstractButton(this.type, this.size);
}
如果您使用的是Flutter,请从小部件类中扩展您的类
Extend your class from widget class if you're using flutter
这篇关于Dart中的字符串文字类型模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!