Search code examples
javascriptreactjsarraystypescriptmapping

How to type a map method with react typescript?


I'm having a map method and expecting it to return a new array. And I'm having an error

Property 'id' does not exist on type 'never'

I think it's because I didn't type the map method variables. How can I do it ?

type Props = {
  authors: [];
  onFinish: () => {};
};

    const NewTask: FC<Props> = ({ authors, onFinish }) => {
    return (
      <select
        onChange={(e) => setAuthor(e.target.value)}
        defaultValue="select"
      >
        <option value="select" disabled>
          Select Author
        </option>
        {authors.map((author) => (
          <option key={author.id} value={author.author_name}>            // author keys are error sublimed
            {author.author_name}
          </option>
        ))}
      </select>
      )
    }


Solution

  • You're getting the error because you didn't define the type for authors. To fix the error, you need to provide a type for the authors prop:

    type Author = {
      id: string;
      author_name: string;
    };
    
    type Props = {
      authors: Author[];
      onFinish: () => void;
    };
    
    const NewTask: FC<Props> = ({ authors, onFinish }) => {
      // ...
    };