// 1. 允许变体值的键可以是字符串,也可以是布尔值(为了开发体验,允许传 true/false) import { mergeClass } from "./merge-class"; // 但底层存储我们统一视为字符串处理 type VariantValue = string | boolean; type VariantsConfig>> = { base?: string; variants?: V; compoundVariants?: Array< // 修改这里:允许 compoundVariants 的值是 VariantValue,而不仅仅是 keyof V[K] Partial<{ [K in keyof V]: VariantValue }> & { class: string } >; }; // 2. 修改 Props 定义,允许传入 boolean,因为 JS 对象 key 访问时,boolean 会被转为 string type VariantProps>> = Partial<{ [K in keyof V]: keyof V[K] | boolean; }>; export function createClassRecipe< V extends Record>, >(config: VariantsConfig) { return function (props: VariantProps = {}): string { const classes: string[] = []; if (config.base) classes.push(config.base); if (config.variants) { for (const [key, map] of Object.entries(config.variants)) { const value = props[key]; // 运行时修复:如果传入的是 boolean true,需要转为字符串 "true" 才能匹配 map const stringifiedValue = String(value); if (value && map[stringifiedValue]) { classes.push(map[stringifiedValue]); } } } if (config.compoundVariants) { for (const cv of config.compoundVariants) { const match = Object.entries(cv) .filter(([k]) => k !== "class") .every(([k, v]) => { const propValue = props[k as keyof V]; // 运行时修复:统一转为字符串比较,确保 "true" === true 能匹配(虽然不建议混用,但要兼容) return String(propValue) === String(v); }); if (match && cv.class) { classes.push(cv.class); } } } return mergeClass(...classes); }; }