React TypeScript中<TimeSlots>传参出现警告,如何定义JSX类型?
Got it, let's fix this TypeScript warning and structured object array issue step by step. Here's how you can properly define types for your <TimeSlots> component in React TypeScript:
1. Define Base Types for Your Time Slot Items
First, create a type for individual time slot objects. To make it type-safe, we'll restrict the day field to valid weekday strings (instead of allowing any arbitrary string):
// Restrict weekday values to a fixed set of valid options type WeekDay = 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sunday'; // Define the shape of a single time slot item type TimeSlotItem = { dayIndex: number; day: WeekDay; // Add any other properties your time slots need here (e.g., startTime, endTime) // startTime?: string; // endTime?: string; };
2. Define Props Type for the TimeSlots Component
Next, create a props type that specifies the hours prop as an array of your TimeSlotItem type:
type TimeSlotsProps = { hours: TimeSlotItem[]; };
3. Apply the Props Type to Your Component
Use this props type when defining your TimeSlots component—this tells TypeScript exactly what shape the input props should have:
import React from 'react'; const TimeSlots: React.FC<TimeSlotsProps> = ({ hours }) => { // Your component logic and JSX rendering here return ( <div className="time-slots"> {hours.map((slot, idx) => ( <div key={idx} className="time-slot"> {slot.day.charAt(0).toUpperCase() + slot.day.slice(1)} (Index: {slot.dayIndex}) </div> ))} </div> ); };
4. Use the Component Safely
Now when you use <TimeSlots> with your existing code, TypeScript will validate that the hours array matches your defined type—no more warnings or type errors:
// This will work perfectly and pass TypeScript checks <TimeSlots hours={[{ dayIndex: 1, day: 'monday' }]}/>
Why This Fixes Your Issue
The original warning/error happened because TypeScript couldn't infer the exact shape of the hours prop (it was either any or unknown). By explicitly defining the types, you're telling TypeScript exactly what properties and value types to expect, making your code safer and eliminating those annoying warnings.
If you ever need to add more properties to your time slots, just update the TimeSlotItem type—TypeScript will automatically enforce the new shape everywhere the component is used.
内容的提问来源于stack exchange,提问作者Jennifer

