233

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.

13
  • Why do you need {} here React.Component<Props, {}>?
    – Siya Mzam
    Commented Jan 13, 2018 at 14:29
  • @brandNew I changed into void, also object, but the same!
    – S. N
    Commented Jan 13, 2018 at 14:30
  • What happens when you just pass the Props and nothing else?
    – Siya Mzam
    Commented Jan 13, 2018 at 14:31
  • @brandNew class App extends React.Component<Props> { also returns the same error as before!
    – S. N
    Commented Jan 13, 2018 at 14:33
  • And when you pass any?
    – Siya Mzam
    Commented Jan 13, 2018 at 14:35

19 Answers 19

221

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>
  );
}
5
  • 19
    Whilst this might resolve the error, this is really bad practice. You should be specific about the props you pass down to a component
    – Jon Wyatt
    Commented May 6, 2021 at 8:16
  • 5
    @JonWyatt in some cases the component itself is the problem: I first encountered this when using a 3rd-party-lib (AntD) in 2019 and the error showed up even when we passed correctly all the required props.
    – CPHPython
    Commented May 7, 2021 at 10:12
  • 1
    i was able to run the app at dev environment when apply this solution but when deploy on netlify it shout about it :)
    – Assay Khan
    Commented Mar 22, 2023 at 14:10
  • I think the "bad practice" note is a little arbitrary. The props themselves still have to match expected types (at-least they appear to in my experience.) It's a destructured form of the common practice of passing a bucket of stuff via an object where you really don't actually have to be more specific - you're just hiding it under a label. Both cases allow you to pass collections of things through calls without having to change multitudes of places with every structural change change as would be necessary if you were to pass every single primitive every single time. Commented Dec 8, 2023 at 23:32
  • This solved my issue, I don't know why this is so far down. It is very simple and if you have a typed object you are specific about the props coming in.
    – Kai Durai
    Commented Feb 29 at 0:15
85

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;
0
27

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!

5
  • Of course, if you are missing some compulsory arguments it will show error. If you want optional arguments i am adding code to how to achieve this in original answer. And you can accept the answer if it answers your question.
    – Swapnil
    Commented Jan 13, 2018 at 20:14
  • SN, you should accept one of the answers above as the accepted answer because they do indeed answer your question. Commented Jan 28, 2019 at 13:30
  • @S.N please accept the answer if it solved your problem correctly
    – Swapnil
    Commented Dec 4, 2019 at 11:50
  • 1
    thanks for the answer, after I had applied other ways to do the task, this way is the best Commented Dec 22, 2019 at 12:36
  • Thanks ... adding a props interface resolved it for me.
    – Jaza
    Commented Jun 14, 2021 at 20:27
8

Insted of <YourComponent product={product} /> use <YourComponent {...product} />

6

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)}
    />
  );
}
2
  • 1
    It hurts to look at this solution, but like you said, as hacky as the other solutions go - this is just as good(or bad) :D Commented Dec 3, 2021 at 19:41
  • 1
    Instead of using <Comp {...(props as any)} />, it appears you can use <Comp {...props} {...{}} />. The additional {...{}} seems to be enough to match the IntrinsicAttributes type that React adds on while preserving the props type. Still not ideal, but better than using "as any". :) Commented Jan 13, 2023 at 6:05
6

For functional components, this syntax solves this error without React.FC boilerplate:

interface FooProps {
  foo: FooType
}

function FooComponent({ foo }: FooProps): ReactElement {
  ...
}
6

I was doing this:

function Post({ post }: Post) { ... }

I had to do this:

function Post({ post }: { post: Post }) {...}
4

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

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.

0
3

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.

3

If you're blind like me, you may bump into the following.
Instead of:

interface TimelineProps {
    width: number;
}

const Timeline: FC = (props: TimelineProps) => {
... 

Do:

const Timeline: FC<TimelineProps> = (props: TimelineProps) => {
                        ^^^
2

What worked for me is simply changing the child Component type from React.FC to JSX.Element

Before (warning)

const Component: React.FC = () => {

After (no warning)

const Component = (): JSX.Element => {

1
  • Worked fine. '''const DataTable = (props: any): JSX.Element => { const columns = props.columns; const items = props.items;''' Commented Feb 4 at 4:16
2

In my case, the component was wrapped using React.memo:

export const NonSavedIcon = React.memo<any>(({
  bg='primary',
  borderColor='red.200',
}:{
  bg?: string;
  borderColor?: string;
}) => {
  return (<Box w='0.5rem' h='0.5rem' bg={bg} borderStyle='solid' borderWidth={1} borderColor={borderColor} borderRadius='full' />)
})

And to solve the error (Type '...' is not assignable to type 'IntrinsicAttributes'), I have replaced React.memo<any> with React.memo. So now TypeScript will automatically infer the type and the error is gone.

1

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.

1
  • 3
    No, He had the interface defined on both files. So it shouldn't have been an issue. Commented Aug 9, 2020 at 20:44
1

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 {};
    },
});
1

You can stop this error on your tsconfig file

inside your tsconfig.json file, I guess the "suppressExcessPropertyErrors": true is set to false or probably not anymore, so add it and your error will go away

Technically the error will still be there, but ts would pass it for you

1
  • I get a warning from that: Option 'suppressExcessPropertyErrors' is deprecated and will stop functioning in TypeScript 5.5. Specify compilerOption '"ignoreDeprecations": "5.0"' to silence this error.ts Commented Mar 2 at 11:53
0

For components, it may be because you wrote your component like this:

    <ClearButton 
        text={"Clear board"} 
        isAnimationInProgress={isAnimationInProgress}
        callSetOptionMethod={clearBoard}
     >
     // empty space here
    </ClearButton>

Instead of this:

    <ClearButton 
        text={"Clear board"} 
        isAnimationInProgress={isAnimationInProgress}
        callSetOptionMethod={clearBoard}
    ></ClearButton>
0

I bet you defining you are props like this

const Skills = (skills: string[]) => {
  return (
   ...
  )
}

try this instead

const Skills = ({skills}: {skills: string[]}) => {
  return (
    ...
  )
}
-1

Just spread the passing props like {...searchval} . and in the component use the props and assign the type original type of searchval.This should work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.