首页 > 解决方案 > 纱线 2 升级似乎破坏了打字稿类型,同一项目的纱线 1 安装在哪里成功?

问题描述

我一直在尝试升级 typescript monorepo 以使用 yarn 2,但遇到了 typescript 不再能够确定某些反应道具的问题。由于这是在纱线 1.x 中工作的,我认为必须在纱线 1.x 中添加一些必须在纱线 2.x 中显式定义的隐式依赖项?在查看项目依赖项和 node_modules 数小时后,我无法确定生产 repo 中需要更改的内容,因此我创建了一个示例项目来重现该问题。希望有人能够指出我所缺少的。

/lib/component/Button.tsx

import React from "react";
import { Button as MuiButton, ButtonProps as MuiButtonProps } from "@material-ui/core";

type ButtonProps = {
  name: "alice" | "bob";
} & MuiButtonProps;

const Button = React.forwardRef<HTMLButtonElement, ButtonProps>((props: ButtonProps, ref) => {
  const { name, ...other } = props;
  return <MuiButton ref={ref} {...other}>hello {name}, click me</MuiButton>;
});

export default Button;
export type { ButtonProps };

/apps/ts-example/App.jsx

import { Button } from "components";

const App = () => {
  return <Button name="bob" variant="outlined" />;
};

export default App;

通过 yarn 1.x 安装所有内容后,我可以将鼠标悬停在“名称”道具上并接收类型信息,如下所示。此外,如果提供的 prop 值不是“alice”或“bob”,您会收到预期的类型错误。

在此处输入图像描述

通过 yarn 2.x 安装后,当我将鼠标悬停在“名称”道具上时,我只会得到一个“字符串”类型(如下所示)。此外,即使提供的不是“alice”或“bob”,typescript 也不会为 prop 提供任何错误。这是有道理的,因为打字稿似乎不再理解类型定义。

在此处输入图像描述

我观察到,如果我删除文件中与 MuiButtonProps 的类型交集,我可以获取“名称”道具的类型信息lib/components/Button.jsx。然而,这会导致该类型的结果不知道底层 Material-UI 按钮的“基础”道具。下面是修改后的类型定义。

type ButtonProps = {
  name: "alice" | "bob";
};

结果如下:

在此处输入图像描述

我希望根据我上面概述的内容,问题很明显,但如果还不够,这里是重现问题的示例存储库。https://github.com/jereklas/ts-example

标签: reactjstypescriptmaterial-uiyarnpkgyarnpkg-v2

解决方案


事实证明,我的 yarn.lock 文件已被删除并使用不同的@material-ui/types版本重新生成,这导致了我的所有问题。它需要是 5.1.0 而不是 5.1.8

- "@material-ui/types@^5.1.0":
-   version "5.1.0"
-   resolved "https://registry.yarnpkg.com/@material-ui/types/-/types-5.1.0.tgz#efa1c7a0b0eaa4c7c87ac0390445f0f88b0d88f2"
-   integrity sha512-7cqRjrY50b8QzRSYyhSpx4WRw2YuO0KKIGQEVk5J8uoz2BanawykgZGoWEqKm7pVIbzFDN0SpPcVV4IhOFkl8A==
+ "@material-ui/types@npm:^5.1.0":
+   version: 5.1.8
+   resolution: "@material-ui/types@npm:5.1.8"
+   peerDependencies:
+     "@types/react": "*"
+   peerDependenciesMeta:
+     "@types/react":
+       optional: true
+   checksum: 543af1b4c0ba8c62f6b4a7f64fd17c8b705c4942c62d4971604e07bb207b834fe7bda97f31d223dc448f66673eb39ceb80b151ddb5ad076506fe515360d572ea
+   languageName: node
+   linkType: hard

推荐阅读