0

In my simple typescript/react app, when I'm trying to map an array of objects, I'm getting an error that property 'title' does not exist on type 'object'.

const Todo = () => {
  const [todos, setTodos] = useState<object[]>([])
  const [title, setTitle] = useState<string>('')
  const [body, setBody] = useState<string>('')

  const onSubmit = (e: React.FormEvent<HTMLFormElement>): void => {
    e.preventDefault()

    const todo = {
      title: title,
      body: body
    }

    setTodos([todo, ...todos])
    setTitle('')
    setBody('')
  }
  return (
    <>
      <form onSubmit={onSubmit}>
        <input value={title} onChange={e => setTitle(e.target.value)} />
        <input value={body} onChange={e => setBody(e.target.value)} />
        <button>submit</button>
      </form>
      todos:
      {todos.map((todo) => <div><h3>{todo.title}</h3>
        <p>{todo.body}</p></div>)}
    </>
  );
}
3
  • Why are you typing todos as object[]? Commented Sep 3, 2019 at 11:50
  • update this to any const [todos, setTodos] = useState<any[]>([]) Commented Sep 3, 2019 at 11:53
  • If not, i'm getting an error Argument of type '{ title: string; body: string; }[]' is not assignable to parameter of type 'SetStateAction<never[]> on setTodos. Commented Sep 3, 2019 at 11:54

1 Answer 1

1

It fails because you say todos are object[], but the object type has no properties associated to it. If you change it to the example bellow, it should work.

const [todos, setTodos] = useState<{title: string, body: string}[]>([])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.