skip to Main Content

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>
      )
    }

3

Answers


  1. 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 }) => {
      // ...
    };
    
    Login or Signup to reply.
  2. You’ve declared author as having type [].

    As a Javascript value, [] is a literal empty array, that can have any values added to it.

    As a Typescript type, [] is a tuple – specifically, it’s an empty tuple which can never contain any values of any type.

    When you’re iterating authors

    authors.map((author) => { ... })
    

    … Typescript infers the type of author based on the type of authors. Since you’ve declared that authors contains no values, it rightly warns you that author has the never type, hence Property 'id' does not exist on type 'never'.

    As other folks have pointed out, you just need to provide an appropriate type for authors, e.g.

    type Author = {
      id:          string;
      author_name: string;
    };
    
    type Props = {
      authors:  Author[];
      onFinish: () => void;
    };
    
    Login or Signup to reply.
  3. You can try with this

    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, index) => (
          <option key={index} value={author.author_name}>            // author keys are error sublimed
            {author.author_name}
          </option>
        ))}
      </select>
      )
    }
    

    Or you should check if you are getting the author object with id and author_name keys

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search