Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS2740 Type is missing the following properties from ReadOnly<MyInterface> error in React Native with TypeScript app

Since StatelessComponent is deprecated, I am trying to turn all the components into classes.

I have an interface, for example:

interface MyInterface{
    prop1: number;
    prop2: boolean;
}

And I use it in the class:

class MyComponent extends React.Component<MyInterface> {
   ...
   public render(){...}
}

And when I try to use MyComponent like this:

<MyComponent 
    prop1={3}
    prop2={false}
/>

I get this error:

TS2740: Type {prop1: 3, prop2: false} is missing the following properties from type ReadOnly: render, context, setState, forceUpdate, and 3 more.

Is there any workaround to this?

like image 377
romin21 Avatar asked Dec 19 '18 13:12

romin21


2 Answers

I finally solved the problem by changing the declaration of the class to class MyComponent extends React.Component<any, MyInterface>.

like image 92
romin21 Avatar answered Nov 11 '22 08:11

romin21


I had a similar case where I have encountered this error: Type '{ label: string; value: string; }' is missing the following properties from type ReadOnly is missing the following properties from type length, pop, push, concat, and 15 more.

I had this following code:

interface IState {
  currentEnvironment: IEnvironment;
  environmentOptions: IEnvironment[];
}
interface IEnvironment {
  label: string;
  value: string;
}

I was initializing the states of array***(In this case environment options)*** as :

public state = {
    currentEnvironment: { label: '', value: '' },
    environmentOptions: [],
  };

Initializing the state more specifically has resolved issue in my case which goes like:

public state = {
    currentEnvironment: { label: '', value: '' },
    environmentOptions: [{ label: '', value: '' }],//Also initializing the properties of the Interface
  };
like image 45
Bhardwaj Avasarala Avatar answered Nov 11 '22 08:11

Bhardwaj Avasarala