error TS2352: Conversion of type 'never[]' to type 'Anime'
при билде мне выдаёт:
error TS2352: Conversion of type 'never[]' to type 'Anime' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type 'never[]' is missing the following properties from type 'Anime': mal_id, id, images, title, and 9 more.
5 AnimeList = []; ~~~~~~~
а у меня с animeList только:
const [animeList, setAnimeList] = useState<Anime[]>([])
Ответы (2 шт):
Проблема в том, что TS видит, что animeList объявлен как Anime[], но при этом туда помещается пустой массив, который по умолчанию имеет тип never[].
Решение "в лоб":
const [animeList, setAnimeList] = useState<Anime[]>([] as Anime[]);
Тут мы явно указываем, что пустой массив не пустой, а всё такие Anime[].
Но это не совсем корректное решение.
Nullable-элементы массива:
const [animeList, setAnimeList] = useState<(Anime | null)[]>([]);
А тут уже каждый элемент массива или Anime или null, но тут потребуется дополнительная проверка в процессе перебора.
const [animeList, setAnimeList] = useState<(Anime | null)[]>([]);
// Когда массив пустой
if (animeList.length === 0) {
return (
<span>Список пуст</span>
)
}
// Когда в массиве что-то есть
return animeList.map((item, index) => {
return item !== null ? (
<span key={ index }>{ item.name }</span>
) : null
})
Массив или null
Тут вариант, что это массив или null, по умолчанию useState может содержать как null, так и массив с данными.
const [animeList, setAnimeList] = useState<Anime[] | null>(null);
// Когда массива нет
if (animeList === null) return null;
// Когда массив пустой
if (animeList.length === 0) {
return (
<span>Список пуст</span>
)
}
// Когда в массиве что-то есть
return animeList.map((item, index) => (
<span key={ index }>{ item.name }</span>
))
Нет такой проблемы:
import { useState } from 'react';
class Anime {
smth = 0;
}
const [animeList, setAnimeList] = useState<Anime[]>([])
Ошибка будет только если ты массив посеял:
useState<Anime>([])