You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 09:07:42