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.
2
Answers
First, you might want to define the task object as a separate type or interface for better readability and reusability. For example:
Then, in your App.tsx, use the Task[] type for your state:
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.
Not on the topic of the problem, but I also want to note that you have small mistake, you typed
tasks
property as aTuple
, not asArray
. Difference in below code (instead of "string" you can use any other type, obviously):