reactjs - Tipo 'TaskListProps[]' no se puede asignar al tipo TaskListProps
Estoy teniendo problemas para manejar los tipos mientras programo una aplicación en TypeScript, tengo la TaskListPorps como mi interfaz
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;
}
];
}
Un componente TaskList
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;
Y en mi componente principal de la aplicación, cuando intento asignar una lista de tareas desde una API, TypeScript dice que el tipo 'TaskListProps[]' no es asignable.
El componente App.tsx tal como está
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;
El error ocurre justo en la línea <TaskList tasks={tasks} />.
He intentado resolverlo encapsulándolo en un array, pero no funcionó.
Respuesta #1
No relacionado con el tema del problema, pero también quiero señalar que tienes un pequeño error, escribiste la propiedad tasks como un Tuple, no como un Array. La diferencia en el código a continuación (en lugar de "string" puedes usar cualquier otro tipo, obviamente):
type StringTuple = [string]; <- It means that in array expected only 1 element
type StringArray = string[]; <- Any length
const tuple: StringTuple = ['a', 'b']; <- Here error "Type ... is not assignable to .."
const list: StringArray = ['a', 'b']; <- It works
