Home > Enterprise >  having trouble adding types to this entity ( new to typescript ) *Solved*
having trouble adding types to this entity ( new to typescript ) *Solved*

Time:05-02

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: boolean;
  label: string;
  key: number;
}
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

Update I found my solution here: Best way to create entity objects with TypeScript?

my updated code:

type TodoProps = {
  complete: boolean;
  label: string;
  key: number;
};
interface Todo extends TodoProps {}
class Todo {
  constructor({ complete, label, key }: TodoProps) {
    this.complete = false;
    this.label = label;
    this.key = Date.now();
  }
}

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