【发布时间】:2021-04-01 04:21:45
【问题描述】:
我一直在使用 Material UI 处理 TypeScript 问题所需的这种结构,这真的让我很烦恼,每次我想为组件设置样式时,我都需要记住如何将 2 个不同的功能组合成可以产生的东西一个钩子(我可以用一个 sn-p 来解决它,但这对我来说从来都不是正确的):
const useStyles = makeStyles((theme: Theme) =>
createStyles({
...styles
})
);
所以我当然尝试通过将其抽象为 1 个函数来使其更加干燥,但我似乎无法理解如何使这些类型为此工作。这是我笨拙的尝试:
const makeUseStyles = (styleFunc: (th: Theme) => CSSProperties | CreateCSSProperties<{}>) =>
makeStyles((theme: Theme) => {
const st = styleFunc(theme);
return createStyles(st);
});
这会产生 2 个问题:createStyles 不接受 st 作为参数:
Type 'unknown' is not assignable to type 'PropsFunc<(value: JSSFontface, index: number, array: JSSFontface[]) => unknown, CreateCSSProperties<(value: JSSFontface, index: number, array: JSSFontface[]) => unknown>>'
makeUseStyles 返回的函数突然期待props 类型为(value: JSSFontface, index: number, array: JSSFontface[]) => unknown 的必需参数。
所以我假设,因为我的尝试失败了,这就是为什么首先需要 2 个单独的函数来安抚 TypeScript,但是让我很困扰的是编译器会决定抽象(感觉就像它完成了所有工作一样)我尝试弄干我的样式代码的那一刻)。所以我的问题是:为什么?
【问题讨论】: