typescript - 类型 tailwind types 上不存在属性 'white'
我刚接触 TypeScript,我正在尝试弄清楚自己做错了什么。
我已经安装了 @types/tailwindcss 版本 2.2.4,并且我正在尝试创建一个应该使用主题颜色的 toast,这里是代码:
import iziToast, {IziToastSettings} from "izitoast";
import resolveConfig from "tailwindcss/resolveConfig";
import tailwindConfig from "@base/tailwind.config" ;
class Toast {
config = resolveConfig(tailwindConfig);
colors = this.config.theme!.colors!;
default: IziToastSettings = {
messageColor: this.colors.white,
iconColor: this.colors!.white,
position: "topRight",
}
}
但是 this.colors.white 会抛出一个错误,说:
TS2339: Property 'white' does not exist on type 'TailwindThemeColors'我在 @types/tailwindcss 中追踪了 TailwindThemeColors,它是:
export type TailwindThemeGetter<T> = ((getters: { theme: any; negative: any; colors: any; breakpoints: any }) => T) | T;
export type TailwindThemeColors = TailwindThemeGetter<TailwindValuesColor>;
export interface TailwindValuesColor {
readonly [key: string]: TailwindColorValue;
}
我从中移除了这一部分 ((getters: { theme: any; negative: any; colors: any; breakpoints: any }) => T) |,然后它就可以工作了,但你知道,这是一个外部包,不应该这样操作。
我正在尝试理解我哪里做错了?以及这行代码我删掉了,因为在查阅 TypeScript 文档时没有找到它。
有没有办法在不只是忽略错误的情况下设置正确的类型?
答案#1
export type TailwindThemeGetter<T> = ((getters: { theme: any; negative: any; colors: any; breakpoints: any }) => T) | T;
TailwindThemeGetter<T> 要么是一个函数,要么是 T,所以 TypeScript 要求你测试它是哪一个。类似这样:
class Toast {
config = resolveConfig(tailwindConfig);
white = typeof (theme?.colors) === 'object' ? theme.colors?.['white'] : 'white';
default: IziToastSettings = {
messageColor: this.white,
iconColor: this.white,
position: "topRight",
}
}
你需要处理当它是一个函数的情况,所以你可以有一个默认颜色(我上面做了),或者抛出异常。
