Ad

Map An Array Of Objects With Typescript

- 1 answer

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>)}
    </>
  );
}
Ad

Answer

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}[]>([])
Ad
source: stackoverflow.com
Ad