类型“{}”不可分配给类型“IntrinsicAttributes & IntrinsicClassAttributes”

IT技术 json reactjs typescript
2021-04-04 16:35:07

我目前正在制作一个简单的react应用程序。这是我的index.tsx

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(
  <App />,
  document.getElementById('root') as HTMLElement
);
registerServiceWorker();

我有我的 app.tsx

    import * as React from 'react';
import SearchBar from '../containers/price_search_bar';

interface Props {
  term: string;
}

class App extends React.Component<Props> {

  // tslint:disable-next-line:typedef
  constructor(props) {
    super(props);
    this.state = {term: '' };
  }

  render() {
    return (
      <div className="App">
        <div className="App-header">
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          this is my application.
        </p>
        <div>
            <form>
            <SearchBar term={this.props.term} />
            </form>
        </div>
      </div>
    );
  }
}

export default App;

还有我的搜索栏容器:

    import * as React from 'react';

interface Props {
    term: string;
}

// tslint:disable-next-line:no-any
class SearchBar extends  React.Component<Props> {

    // tslint:disable-next-line:typedef
    constructor(props) {
        super(props);
        this.state = { term: '' };
    }

    public render() {
        return(
            <form>
                <input 
                    placeholder="search for base budget"
                    className="form-control"
                    value={this.props.term}
                />
                <span className="input-group-btn" >
                    <button type="submit" className="btn btn-secondary" >
                        Submit
                    </button>
                </span>

            </form>
        );
    }
}

export default SearchBar;

最后我有我的tsconfig.json

{
  "compilerOptions": {
    "outDir": "build/dist",
    "module": "esnext",
    "target": "es5",
    "lib": ["es6", "dom"],
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    "rootDir": "src",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": false,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "noUnusedLocals": true
  },
  "exclude": [
    "node_modules",
    "build",
    "scripts",
    "acceptance-tests",
    "webpack",
    "jest",
    "src/setupTests.ts"
  ]
}

我在错误之后不断收到不同的错误,每当我修复一个错误时,另一个错误出现时,我不确定我做了什么使它表现得像这样。这是最新的错误:

./src/index.tsx
(7,3): error TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<App> & Readonly<{ children?: ReactNode; }> & Reado...'.
  Type '{}' is not assignable to type 'Readonly<Props>'.
    Property 'term' is missing in type '{}'.

我试图通过修改我的来修复它,tsconfig.json但仍然出现同样的错误,我做错了什么以及为什么typescript像这样。我对此很陌生,通过这个例子,我试图了解 react 是如何一起工作的。

6个回答

通过声明一个完全传递给组件的对象,解决了很多“不可分配到类型‘IntrinsicAttributes & IntrinsicClassAttributes ”类型的错误(微软已关闭问题)。

使用 OP 的示例,而不是使用term={this.props.term},使用{...searchBarProps}来让它工作:

render() {
  const searchBarProps = { // make sure all required component's inputs/Props keys&types match
    term: this.props.term
  }
  return (
    <div className="App">
      ...
      <div>
          <form>
          <SearchBar {...searchBarProps} />
          </form>
      </div>
    </div>
  );
}
很遗憾看到在 21 年 12 月我仍然需要这样做来绕过检查器。
2021-05-24 16:35:07
天哪,我这几天一直在想办法解决这个问题。你是救命稻草。
2021-06-02 16:35:07
@ZunaibImtiaz 深入研究Typescript 的checker.ts它很可能是因为intrinsicAttributes不需要执行分配给的块,因为没有显式的JsxAttributes来比较该组件的调用(isComparingJsxAttributes可能是假的)。如果您真的需要确定是否是这种情况,请尝试调试 Typescript 的源代码。
2021-06-03 16:35:07
善良。你是救命稻草!
2021-06-06 16:35:07
善良。我希望这不是必需的。
2021-06-07 16:35:07

这里的问题不在于您的 tslint 设置。看下面的代码片段:

interface SearchBarProps {
  term: string;
  optionalArgument?: string;
}

interface SearchBarState{
  something: number;
}

class SearchBar extends React.Component<SearchBarProps, SearchBarState> {
  constructor(props: SearchBarProps){
    super(props);

    this.state = {
      something: 23
    };
  }

  render() {
    const {something} = this.state;
    return (
      <div>{something}</div>
    )
  }
}

class SearchBar extends React.Component<SearchBarProps, SearchBarState> {SearchBarPropsSearchBarState分别表示组件的预期props类型和状态类型SearchBar使用typescript时必须提供 propTypes 和 stateType。
您可以通过使用关键字来避免提供类型,any但如果您真的想利用typescript的优势,我强烈建议您不要走这条“邪恶”的道路。在您的情况下,您似乎没有指定状态类型并使用它,修复将解决此问题。

编辑 1
在 interface 中SearchBarPropsoptionalArgument由于我们?在它前面添加了一个问号,因此成为一个可选参数,因此<SearchBar term='some term' />即使您不optionalArgument显式传递也不会显示任何错误
希望这能解决您的问题!

等等,添加了这样的东西<SearchBarPrice term="s"/> ,它确实有效!
2021-05-27 16:35:07
感谢您的回答,但是如果我使用这个容器而不是另一个容器,我仍然面临同样的错误。
2021-05-28 16:35:07
SN,您应该接受上述答案之一作为已接受的答案,因为它们确实回答了您的问题。
2021-06-04 16:35:07
@SN如果正确解决了您的问题,请接受答案
2021-06-07 16:35:07
当然,如果您缺少一些强制参数,它会显示错误。如果您想要可选参数,我将在原始答案中添加代码以说明如何实现这一点。如果它回答了您的问题,您就可以接受答案。
2021-06-21 16:35:07

您只需要正确声明组件类型以包含 props 类型:

interface IMyProps {
    myValue: boolean,
}

const MyComponent: React.FC<IMyProps> = (props: IMyProps) => {
    ...
}

export default MyComponent;

然后您可以将其用作:

import MyComponent from '../MyComponent';

...

return <MyComponent myValue={true} />

瞧,typescript很高兴。关于它的好处是typescript现在只检查传递它们实际存在于 props 接口中的参数(可以防止拼写错误等)。

对于标准组件,它类似于(Swapnill 的示例中已有的内容):

class MyComponent extends React.Component<IMyProps, IMyState>{
    constructor(props: IMyProps){}
}
export default MyComponent;

刚刚有同样的问题。

您在 App 类的 Prop 接口上定义了名为 term 的成员,但在创建 App 元素时没有提供值。

请尝试以下操作:

ReactDOM.render(<App term="Foo" />, document.getElementById('root') as HTMLElement);

我也面临同样的问题。添加以下代码以使用 .tsx 组件。

export interface Props {
  term: string;
}

或者

export type Props = {
  term ?: string;
}

我不知道确切的原因,但我认为 typescript 在编译阶段标记了类型错误。请让我知道这对你有没有用。