React+TypeScript入门报错:属性'todos'不存在于ToDoList组件类型中
Hey there! No worries—this is a super common hiccup when you’re starting out with TypeScript in React. TypeScript is just being strict (in a good way!) to make sure we’re clear about what props our components can accept. Let’s walk through how to fix this:
1. Define Types for Your Todo Data and Component Props
The error happens because TypeScript has no idea that your ToDoList component expects a todos prop. First, let’s define the shape of a single todo item, then the props that ToDoList will take:
// Define what a single todo item looks like interface Todo { id: number; name: string; } // Define the props that ToDoList needs interface ToDoListProps { todos: Todo[]; }
2. Update Your ToDoList Component to Use These Types
Now, we’ll tell TypeScript that ToDoList accepts props matching the ToDoListProps interface. Here’s how a functional component version would look:
const ToDoList: React.FC<ToDoListProps> = ({ todos }) => { // Your component logic here (e.g., mapping over todos to render items) return ( <ul> {todos.map(todo => ( <li key={todo.id}>{todo.name}</li> ))} </ul> ); };
3. Improve Type Safety for Your TODOS Array
Instead of using the vague object[] type, let’s type our todo array with the Todo interface we created—this ensures it matches exactly what ToDoList expects:
const TODOS: Todo[] = [ { id: 1, name: 'Todo 1' }, { id: 2, name: 'Todo 2' } ];
4. Double-Check Your App Component
Make sure your App is passing the todos prop correctly to ToDoList. Here’s a complete example of how App might look:
const App: React.FC = (): JSX.Element => { return ( <div className="app"> <h1>My Todo List</h1> <ToDoList todos={TODOS} /> </div> ); };
That should clear up the error! TypeScript now knows exactly what props ToDoList accepts, so it won’t throw that "property doesn’t exist" warning anymore.
内容的提问来源于stack exchange,提问作者Tudor Apostol

