Rap*_*117 21 typescript reactjs tsx tailwind-css
我将以下代码导入到我的 .tsx 组件中:
import resolveConfig from 'tailwindcss/resolveConfig';
import tailwindConfig from '../../../tailwind.config.js';
const fullConfig = resolveConfig(tailwindConfig)
Run Code Online (Sandbox Code Playgroud)
如果我随后引用,fullConfig.theme.colors["blue"]["700"]则会收到一条错误消息:
元素隐式具有“any”类型,因为“blue”类型的表达式不能用于索引类型“TailwindThemeColors”。类型“TailwindThemeColors”上不存在属性“蓝色”。
颜色的 Tailwind 类型定义是:
export type TailwindColorValue = string | TailwindColorGroup | TailwindColorFunction;
export interface TailwindValuesColor {
readonly [key: string]: TailwindColorValue;
}
Run Code Online (Sandbox Code Playgroud)
由于该类型没有明确指出这"blue"是一个值并且它可能是一个对象,所以这就是错误的原因(我认为)。
我遇到的另一个问题是我的 中出现错误tsconfig.json,因为我正在导入 JS 文件。添加并"exclude": ["tailwind.config.js"]不能解决问题。
我很确定这是一个 Typescript 问题,而不是 Tailwind 问题......
我的问题是:
"blue"顺风主题中颜色的属性,以及这看起来是由于 Tailwind 输入其resolveConfig返回值所使用的联合类型而出现的问题。本质上,由于联合,TS 不知道 的值fullConfig.theme.colors是对象还是 getter 函数(同样,不知道fullConfig.theme.colors["blue"]是字符串、颜色组对象还是颜色函数) - 大概这是因为这个决定被留下了用户的 tailwind.conf 实现选择,Tailwind 不会推断它。
解决这个问题的最简单方法可能是编写自己的函数,该函数采用您尝试使用的联合类型值并仅返回您想要的特定类型,例如。
import _ from 'lodash';
const asColorObject = (
input: TailwindThemeColors | undefined,
): Exclude<typeof input, Function | undefined> => {
if (_.isFunction(input) || !input) throw new Error();
return input;
};
const fullConfig = resolveConfig(tailwindConfig);
const colorBlue = asColorObject(fullConfig.theme.colors)['blue'];
Run Code Online (Sandbox Code Playgroud)
至于为什么导入 Tailwind 配置会出现错误,请检查TSConfig 中的allowJs和checkJS键。compilerOptions否则,如果您使用 Create React App,则根本不可能采用这种方式,因为您无法从文件夹外部导入文件src。
| 归档时间: |
|
| 查看次数: |
17859 次 |
| 最近记录: |