Home > database >  having trouble adding types to this component ( new to typescript )
having trouble adding types to this component ( new to typescript )

Time:05-03

Im making a small todo app in react to get a taste of typescript. my Todo class is just going to be used for Data entity and it consists of a todo label, complete status, and a key;

interface TodoProps {
  complete: string;
  label: string;
  key: string;
}
class Todo extends Component<TodoProps, any> {
  constructor(label) {
    this.label = label;
    this.complete = false;
    this.key = Date.now();
  }
}

My code editor keeps complaining that this.label, this.complete, and this.key does not exist on type "Todo" any ideas? thanks

CodePudding user response:

The Todo component will be called like this:

<Todo key="key" label="label" complete="complete"  />

key, label and complete are props, you must access it by using the props attribute. To access to your props, you cannot wrote:

this.key = "myKey";

You should do like this:

this.props.key = "myKey";

CodePudding user response:

So in order to access the props on your component, you need to use the props getter:

 constructor(props: TodoProps) {
    super(props);
    this.props.label = props.label;
    this.props.complete = false;
    this.label.key = Date.now();
  }

What I wonder is if you intend to hard code both complete and key then why are they part of props?

why do you allow someone to pass <Todo complete={true} /> if complete gets set to false immediately on construction?

Also, it has been a while since I used class components, but isn't the whole point of this line:

super(props)

to set your props object to be equal to this.props??

  • Related