Тип "WeatherTypes | undefined" не может быть назначен для типа "WeatherTypes". (2322)
Я использую масив обэктов(data), но не могу его типизировать .
Error: Тип "WeatherTypes[] | undefined" не может быть назначен для типа "WeatherTypes[]". Тип "undefined" не может быть назначен для типа "WeatherTypes[]".ts(2322)
Хуки
const [name, setName] = React.useState<string | null>("");
const [city, setCity] = React.useState<string | null>("Киев");
const [country, setCountry] = React.useState<string>("");
const [data, setData] = React.useState<WeatherTypes[]>();
React.useEffect(() => {
axios
.get(
`https://api.openweathermap.org/data/2.5/forecast?appid=************************=${city}&units=metric&lang=ru&cnt=24`
)
.then((response) => {
if (response.status === 200) {
const data = response.data;
setData([data.list[0], data.list[7], data.list[15], data.list[23]]);
setName(data.city.name);
setCountry(data.city.country);
}
});
}, [city]);
types.ts
export interface WeatherTypes {
main?: mainTypes[];
weather?: weatherTypes[];
wind?: windTypes[];
clouds?: cloudsTypes[];
dt_txt?: string;
}
export type mainTypes = {
temp?: number;
humidity?: number;
};
export type weatherTypes = {
description?: string;
icon?: string;
};
export type windTypes = {
speed?: number;
};
export type cloudsTypes = {
all?: number;
};
Ответы (1 шт):
Автор решения: Евгений Платов
→ Ссылка
у вас инициирующее значение undefined (в скобках) а указан тип WeatherTypes[]
const [data, setData] = React.useState<WeatherTypes[]>();
надо как то так
const [data, setData] = React.useState<WeatherTypes[]>([]);