不可分配到类型 IntrinsicAttributes 和 IntrinsicClassAttributes React.js

Muh*_*han 12 typescript reactjs

我已经合作react.js了一段时间。最近,我开始看到如下错误:

Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes'
Run Code Online (Sandbox Code Playgroud)

我不知道发生了什么。我用谷歌搜索了一下,我发现其他人的说法是它是props. 这是我看到的一个场景。而不是:

<MyComponent action={this.state.action} />
Run Code Online (Sandbox Code Playgroud)

以下工作很好:

<MyComponent {...props} />
Run Code Online (Sandbox Code Playgroud)

我想了解什么是IntrinsicAttributesIntrinsicClassAttributes在这件事react。您能否为我提供一个详细的答案,说明为什么会发生此类错误以及这些错误究竟是什么?

Ron*_*nie 11

IntrinsicAttributes 和 IntrinsicClassAttributes

在 TypeScript 中实现的接口。它们影响React.jsxDOM元素的交互,同时使用自定义组件


基本原则

让我们假设你有

interface BarProps {
  foo: string;
}

class Bar extends React.Component<BarProps> {
  ...
}
Run Code Online (Sandbox Code Playgroud)

如果你尝试渲染它

render() {
  return (
    <form>
      <Bar />
    </form>
  );
}
Run Code Online (Sandbox Code Playgroud)

你会得到一个类似的错误;因为您违反了接口类型检查。组件应该有一个强制性的道具,即BarProps在这里作为参数传递。

为了让它工作,你需要做一些类似的事情..

render() {
  return (
    <form>
      <Bar foo="Jack Daniel's"/>
    </form>
  );
}
Run Code Online (Sandbox Code Playgroud)

或者您可以从组件定义本身中删除它。

class Bar extends React.Component<> {
 ...
}
Run Code Online (Sandbox Code Playgroud)

或使foo可选..

interface BarProps{
  foo?: string;
}
Run Code Online (Sandbox Code Playgroud)

想法是实现一致性。

在您的情况下,您正在传递一个未知的道具,即action可能尚未在您的组件中定义。

当你调用你的组件时<MyComponent {...props} />- 它本质上意味着,导入所有可用的道具。

当您显式调用actionprop 时,<MyComponent action={this.state.action} />它会抛出大错误。


提到的错误是非常臭名昭著的。您可以在此React 和 TypeScript调试指南中找到更多见解,其中突出显示了这些错误并分享了可能的修复方法。

你可以阅读更多有关的实施IntrinsicAttributesIntrinsicClassAttributes在这个仓库


Zun*_*iaz 9

深入研究 Typescript 的 checker.ts 可能是因为不需要执行对 internalAttributes 进行分配的块,因为没有显式的 JsxAttributes 来比较该组件的调用(isComparingJsxAttributes 可能为 false)。如果您确实需要确定是否是这种情况,请尝试调试 Typescript 的源代码。

举一个例子,这里打字稿期望好的东西被传递,只有在组件安装时才会被解构。

<MyComponent {...props} />
Run Code Online (Sandbox Code Playgroud)

但是在这里打字稿将 this.state.action 视为未定义或可能为空,因为它永远不确定是否会传递有效值。

<MyComponent action={this.state.action} />
Run Code Online (Sandbox Code Playgroud)

即使你有正确的动作道具类型。它仍然不知道它是否有价值,因此将其视为{}一个空对象并且不能分配给动作。