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

JsonReactjsTypescript

Json Problem Overview


i am currently making a simple react application. this is my 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

    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:

{
  "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.json but 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.

Json Solutions


Solution 1 - Json

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.

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

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

Solution 2 - Json

All you need is to declare the component type properly to include the props type:

interface IMyProps {
    myValue: boolean,
}

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

export default MyComponent;

Then you can use it as:

import MyComponent from '../MyComponent';

...

return <MyComponent myValue={true} />

And voila, typescript is happy. The good thing about it is that typescript is now checking for passing only the parameters they actually exist in the props interface (can prevent typos and so on).

For the standard component it would be something similar to (what's already in Swapnill's example):

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

Solution 3 - Json

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

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> {, SearchBarProps and SearchBarState denote type of expected props and type of state for component SearchBar respectively. You must give propTypes and stateType when you use typescript.
You can avoid giving types by using keyword any but 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.

Edit 1
In interface SearchBarProps, optionalArgument becomes 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 optionalArgument explicitly.
Hope this solves your problem!

Solution 4 - Json

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.

Try the following:

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

Solution 5 - Json

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

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.

Solution 6 - Json

I'm not really proud of that but, considering other solutions in this thread, it seems fair enough.

This example shows a custom version of @react-native-community/slider with some default properties but able to receive (and overwrite) from outside:

function CustomSlider(props: SliderProps) {
  return (
    <Slider
      style={{ width: '100%', height: 40, marginTop: 12 }}
      minimumValue={0}
      minimumTrackTintColor="#000000"
      maximumTrackTintColor="#000000"
      {...(props as any)}
    />
  );
}

Solution 7 - Json

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.

Solution 8 - Json

I keep arriving back here because Volar is raising a similar error in my Vue 3 component. The solution is always that I am returning and empty object for props because my component template has it for convenience but I haven't used it.

When the component is used:

<template>
    <div>
        <MyComponent/> <!-- Squiggly error here -->
    </div>
</template>

The component:

export default defineComponent({
    name: 'MyComponent',
    components: {},
    props: {}, // Remove this
    setup() {
        return {};
    },
});

Solution 9 - Json

I know my answer is somewhat off-topic, but in an Vue3 application I can reproduce the error by assigning the component the props attribute even if no props are passed:

export default defineComponent({ props:{} .... })

Just by removing the props attribute the compiler do not complains anymore.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionS. NView Question on Stackoverflow
Solution 1 - JsonCPHPythonView Answer on Stackoverflow
Solution 2 - JsonVočkoView Answer on Stackoverflow
Solution 3 - JsonSwapnilView Answer on Stackoverflow
Solution 4 - JsonStephen HewisonView Answer on Stackoverflow
Solution 5 - Jsonniraj17View Answer on Stackoverflow
Solution 6 - JsonPedro AndradeView Answer on Stackoverflow
Solution 7 - JsonRoger OliveiraView Answer on Stackoverflow
Solution 8 - JsonavenmoreView Answer on Stackoverflow
Solution 9 - JsonChristian FelixView Answer on Stackoverflow