如何将Tailwind颜色调色板用作Type类型?Next13徽章组件开发
将Tailwind颜色调色板转为Type类型实现Badge组件参数自动补全
当然可以把Tailwind的颜色调色板定义为TypeScript类型,以此实现组件参数的自动补全。以下是具体实现方案:
1. 定义Tailwind颜色相关类型
根据需求,你可以选择只定义颜色名称,或者扩展到包含深浅层级的完整类名:
基础颜色名称类型
type TailwindColor = | 'slate' | 'gray' | 'zinc' | 'neutral' | 'stone' | 'red' | 'orange' | 'amber' | 'yellow' | 'lime' | 'green' | 'emerald' | 'teal' | 'cyan' | 'sky' | 'blue' | 'indigo' | 'violet' | 'purple' | 'fuchsia' | 'pink' | 'rose';
带深浅层级的完整类名类型
如果需要自动补全bg-blue-500、text-red-600这类完整类名,可以扩展类型:
type TailwindColorShade = 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 950; type TailwindColorClass = `bg-${TailwindColor}-${TailwindColorShade}` | `text-${TailwindColor}-${TailwindColorShade}`;
2. 修改Badge组件的Props类型
把color字段的类型替换为上面定义的类型,就能获得自动补全提示:
import React from 'react' type TailwindColor = | 'slate' | 'gray' | 'zinc' | 'neutral' | 'stone' | 'red' | 'orange' | 'amber' | 'yellow' | 'lime' | 'green' | 'emerald' | 'teal' | 'cyan' | 'sky' | 'blue' | 'indigo' | 'violet' | 'purple' | 'fuchsia' | 'pink' | 'rose'; type TailwindColorShade = 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 950; type TailwindColorClass = `bg-${TailwindColor}-${TailwindColorShade}` | `text-${TailwindColor}-${TailwindColorShade}`; type BadgeProps = { text: string color: TailwindColorClass } export const Badge = ({ text, color }: BadgeProps) => { return ( <div className={`flex items-center justify-center p-4 text-center ${color}`} > {text} </div> ) }
3. 适配自定义颜色
如果你的tailwind.config.js里配置了自定义颜色,只需把自定义颜色名称添加到TailwindColor联合类型中即可:
type TailwindColor = | 'slate' | 'gray' | ... // 默认颜色列表 | 'primary' | 'secondary'; // 自定义颜色
4. 灵活兼容任意类名
如果想同时支持预设颜色类的自动补全和任意合法Tailwind类名的输入,可以用string & {}扩展类型:
type TailwindColorClass = (`bg-${TailwindColor}-${TailwindColorShade}` | `text-${TailwindColor}-${TailwindColorShade}`) | (string & {});
内容的提问来源于stack exchange,提问作者devpedrodias
相关产品推荐
相关产品推荐

