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
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:
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
…… Typescript infers the type of
author
based on the type ofauthors
. Since you’ve declared thatauthors
contains no values, it rightly warns you thatauthor
has thenever
type, henceProperty '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.You can try with this
Or you should check if you are getting the author object with id and author_name keys