I’m encountering a type error in my React TypeScript application when trying to pass a hotel object to a form component. The error message is as follows:
Type 'HotelType[] | undefined' is not assignable to type 'HotelType'.
Type 'undefined' is not assignable to type 'HotelType'.ts(2322)
ManageHotelForm.tsx(27, 5): The expected type comes from property 'hotel' which is declared here on type 'IntrinsicAttributes & Props'
these are all the relevant parts of the code:
// page.tsx
const EditHotel = () => {
const {hotelId} = useParams();
const {data:hotel} = useQuery("fetchHotelById", ()=> apiClient.fetchHotelById(hotelId || ""),{ enabled: !!hotelId})
return <ManageHotelForm hotel={hotel} />
}
// HotelType.tsx
export type HotelType = {
_id: string;
userId: string;
name: string;
city: string;
country: string
description: string;
type: string;
adultCount: number;
childCount: number;
facilities: string[];
pricePerNight: number;
starRating: number;
imageURLs: string[];
lastUpdated: Date;
}
//ManageHotelForm.tsx
type Props = {
onSave: (hotelFormData: FormData)=> void
isLoading: boolean,
hotel: HotelType,
}
const ManageHotelForm = ({onSave,isLoading,hotel}: Props) => {
const formMethods = useForm<HotelFormData>()
const {handleSubmit,reset} = formMethods;
useEffect(()=>{
reset(hotel);
},[hotel,reset]);
//fetchHotelById
export const fetchHotelById = async (hotelId: string): Promise<HotelType[]> => {
const response = await fetch(`${API_BASE_URL}/api/my-hotels/${hotelId}`, {
credentials: "include"
})
if (!response.ok) {
throw new Error('Error fetching hotels');
}
return response.json();
}
//Backend route
router.get('/:id',verifyToken, async (req:Request,res:Response)=>{
const id = req.params.id.toString();
try {
const hotel = await Hotel.findOne({
_id: id,
userId: req.userId,
});
res.json(hotel);
} catch (error) {
res.status(500).json({message: "Error fetching hotels"})
}
})
The code is working as expected yet the hotel={hotel} in the Page.tsx is throwing an error. I’m new to typescript so I have yet to know how to make it happy.