TypeScript无法识别属性的类型是否正确



我正在将React中的Material UI Dashboard转换为Typescript,遇到了Typescript编译失败但属性符合报告错误中的标准的问题。短版本:编译此链接Style.jsx文件

const linksStyle = theme => ({
searchButton: {
top: "-50px !important",
marginRight: "22px",
float: "right"
}
});
export default linksStyle;

报告此错误:

TypeScript error in C:/Dev/github/mui-dashboard/src/components/Navbars/AdminNavbarLinks.tsx(269,27):
Argument of type '(theme: any) => { searchButton: { top: string; marginRight: string; float: string; }; }' is not assignable to parameter of type 'Styles<Theme, {}, "searchButton">'.
Type '(theme: any) => { searchButton: { top: string; marginRight: string; float: string; }; }' is not assignable to type 'StyleRulesCallback<Theme, {}, "searchButton">'.
Type '{ searchButton: { top: string; marginRight: string; float: string; }; }' is not assignable to type 'Record<"searchButton", CSSProperties | (() => CSSProperties)>'.
Types of property 'searchButton' are incompatible.
Type '{ top: string; marginRight: string; float: string; }' is not assignable to type 'CSSProperties | (() => CSSProperties)'.
Type '{ top: string; marginRight: string; float: string; }' is not assignable to type 'CSSProperties'.
Types of property 'float' are incompatible.
Type 'string' is not assignable to type '"left" | "right" | "-moz-initial" | "inherit" | "initial" | "revert" | "unset" | "none" | "inline-end" | "inline-start" | undefined'.  TS2345
267 | }
268 | 
> 269 | export default withStyles(linksStyle)(AdminNavbarLinks);
|                           ^
270 | 

从错误的最后一行可以看出,TypeScript期望float具有值之一:'"left" | "right" | "-moz-initial" | "inherit" | "initial" | "revert" | "unset" | "none" | "inline-end" | "inline-start" | undefined',但它确实具有值。如果我从linksStyle.jsx中删除float: "right"属性,代码就会编译,所以这肯定是导致错误的一行。

withStyles是一个Material UI包装函数,在我的例子中是v4.2:类型定义可以在这里看到。

任何关于如何进行的建议都将不胜感激。最初的linksStyle要复杂得多,并且报告了多个类似的问题,我已经将其减少到报告问题的最小值。

我通过两个操作解决了这个问题。感谢@ferhen的指点。

  1. 第一个问题是,如果linkStyles文件从.jsx更改为.tsx,我还没有更改类型。我这样做了,并解决了报告的各种键入警告和错误
  2. 然后,我需要更改所有类型定义为可能字符串列表的属性,如上面的float示例,以使用@ferhan建议的"value" as "value"语法。请注意,这在.jsx文件中不起作用,这不是有效的语法

最新更新