如何移除class-variance-authority变体类型中的null可选值?
当使用class-variance-authority(cva)的VariantProps提取组件props类型时,默认会允许传入null作为variant值(用于重置默认样式)。如果不需要这个特性,可以通过以下两种方式移除null可选值:
方法一:用TypeScript工具类型排除null
直接对VariantProps生成的类型进行处理,用Exclude工具类型剔除null选项:
import { cva, VariantProps } from 'class-variance-authority'; export const checkboxVariants = cva('border ...', { variants: { size: { sm: 'h-4 w-4', md: 'h-5 w-5', lg: 'h-6 w-6', }, }, defaultVariants: { size: 'md', }, }); // 排除size类型中的null,同时保留可选性 type CheckboxProps = Omit<VariantProps<typeof checkboxVariants>, 'size'> & { size?: Exclude<VariantProps<typeof checkboxVariants>['size'], null>; };
方法二:显式定义variant类型约束
先定义不包含null的variant类型,再用satisfies关键字约束cva的variants配置,确保生成的类型不包含null:
import { cva, VariantProps } from 'class-variance-authority'; // 定义仅包含有效值的size类型 type CheckboxSize = 'sm' | 'md' | 'lg'; export const checkboxVariants = cva('border ...', { variants: { size: { sm: 'h-4 w-4', md: 'h-5 w-5', lg: 'h-6 w-6', } satisfies Record<CheckboxSize, string>, }, defaultVariants: { size: 'md', }, }); // 此时VariantProps生成的size类型自动排除null type CheckboxProps = VariantProps<typeof checkboxVariants>;
这两种方法都能让CheckboxProps中的size仅接受'sm' | 'md' | 'lg'或undefined(因为defaultVariants已设置默认值,实际使用时可省略),同时消除Storybook中显示的null可选选项。
内容的提问来源于stack exchange,提问作者Żywy
相关产品推荐
相关产品推荐

