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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48240449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:05:03  来源:igfitidea点击:

Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes

jsonreactjstypescript

提问by S. N

i am currently making a simple react application. this is my index.tsx

我目前正在制作一个简单的反应应用程序。这是我的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();

and here I have my app.tsx

在这里我有我的 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;

and also my search bar container:

还有我的搜索栏容器:

    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;

and finally I have my tsconfig.json:

最后我有我的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"
  ]
}

I keep getting different errors after errors and when ever I fix one error another one appears, I am not sure what I have done that make it behave like this. This is the latest error:

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

./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 '{}'.

I tried to fix it by modifying my tsconfig.jsonbut the same error still appears, what am I doing wrong and why typescript is bahing like this. I am very new to this and by this example I am trying to udnertand how react works all together.

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

回答by CPHPython

I solved a lot of "not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes" type of errors (Microsoft closed issue) just by declaring an object that is passed entirely to the component.

我只是通过声明一个完全传递给组件的对象,解决了很多“无法分配到类型 'IntrinsicAttributes & IntrinsicClassAttributes” 类型的错误(Microsoft 已关闭问题)。

With the OP's example, instead of using term={this.props.term}, use {...searchBarProps}to get it working:

使用 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>
  );
}

回答by Swapnil

The problem here is not with your tslint settings. Look at the following code snippet:

这里的问题不在于您的 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>
    )
  }
}

In class SearchBar extends React.Component<SearchBarProps, SearchBarState> {, SearchBarPropsand SearchBarStatedenote type of expected props and type of state for component SearchBarrespectively. You must give propTypes and stateType when you use typescript.
You can avoid giving types by using keyword anybut I highly suggest you not to follow this "evil" path if you truly want to take advantage of using typescript. In your case it seems that you haven't specified type of state and used it, fixing that will solve this problem.

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

Edit 1
In interface SearchBarProps, optionalArgumentbecomes an optional argument as we add a question mark ?in front of it, so <SearchBar term='some term' />won't show any error even if you don't pass optionalArgumentexplicitly.
Hope this solves your problem!

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

回答by Stephen Hewison

Just had this same problem.

刚刚有同样的问题。

You have member called term defined on the Prop inteface for your App class but you're not providing a value when you create your App element.

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

Try the following:

请尝试以下操作:

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

回答by niraj17

I also faced the same problem. Add below code to work with .tsx components.

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

export interface Props {
  term: string;
}

or

或者

export type Props = {
  term ?: string;
}

I dont know the exact reason, but i think typescript flag the type error during compilation phase. Let me know if it works for you.

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

回答by Roger Oliveira

The issue is that you are not exporting the interface, you should always export the interface props. So:

问题是您没有导出界面,您应该始终导出界面道具。所以:

export interface Props {
  term: string;
}

Is the solution.

是解决方案。