Issue
I'm having issues dealing with types while coding a typescript app, I have the TaskListPorps
as my interface
export default interface TaskListProps {
tasks: [
{
list_id: string;
title: string;
description: string;
status: string;
deleted: boolean;
deleted_at: string;
created_at: string;
updated_at: string;
}
];
}
A TaskList
component
import TaskListProps from '@/types/TaskListProps';
const TaskList: React.FC<TaskListProps> = ({ tasks }) => {
return (
<FlatList
data={tasks}
keyExtractor={(item) => item.list_id.toString()}
renderItem={({ item }) => <Text>{item.title}</Text>}
/>
);
};
export default TaskList;
And on my main App component when I try to assign a list of tasks from an API typescript says that the Type 'TaskListProps[]' is not assignable.
The App.tsx
component as is
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import TaskList from '@/components/TaskList';
import { getTasks } from '@/services/tasks';
import TaskListProps from '@/types/TaskListProps';
const App: React.FC = () => {
const [tasks, setTasks] = useState<TaskListProps[]>([]);
useEffect(() => {
const fetchTasks = async () => {
const tasksData = await getTasks();
setTasks(tasksData);
};
fetchTasks();
}, []);
return (
<View>
<Text>Minhas Tarefas</Text>
<TaskList tasks={tasks} />
</View>
);
};
export default App;
The error occurs right on the <TaskList tasks={tasks} />
line.
I've tried to solve it encapsulating into an array, but didn't worked.
Solution
First, you might want to define the task object as a separate type or interface for better readability and reusability. For example:
export interface Task {
list_id: string;
title: string;
description: string;
status: string;
deleted: boolean;
deleted_at: string;
created_at: string;
updated_at: string;
}
export interface TaskListProps {
tasks: Task[];
}
Then, in your App.tsx, use the Task[] type for your state:
const App: React.FC = () => {
const [tasks, setTasks] = useState<Task[]>([]); // Use Task[] here
useEffect(() => {
const fetchTasks = async () => {
const tasksData = await getTasks();
setTasks(tasksData);
};
fetchTasks();
}, []);
return (
<View>
<Text>Minhas Tarefas</Text>
<TaskList tasks={tasks} />
</View>
);
};
export default App;
This way, your tasks state in App.tsx correctly represents an array of task objects, and the type will align with what TaskList expects as per the TaskListProps interface.
Answered By - berkobienb
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.