I am a newbie in typescript and learning about how types work in Typescript.
I am also using MaterialUIin this project.
I am getting an error saying I am trying to assign an any value to a string variable. But I am trying to give a string value to a string variable.
Let me explain my project:
Here I am receiving a JSON from another folder
import ProjectData from '../../../../data/projectData.json';
Here I am trying to map over ProjectData JSON file, and passing Project to an onClick handler
{ProjectData.map((Project) => {
return ( <Grid item xs={12} sm={12} md={6} lg={4} xl={3}>
<Box onClick={() => { handleCardClick(Project)}}>
....
Here is my handleCardClick function:
const handleCardClick = (Project: ProjectJSONData) => {
setSelectedProject({
projectTitle: {Project.projectTitle},
thumbnail: {Project.projectThumbnail},
userName: {Project.username},
profileImage: {Project.userProfileImage},
openToCollab: {Project.openToCollab},
tags: {Project.tags},
})
};
and my useState:
const [selectedProject, setSelectedProject] = useState<ProjectDataType | null>(null);
These are the two types I have defined:
ProjectJSONData is for the JSON I am receiving
type ProjectJSONData = {
projectTitle: string;
ProjectThumbnail: string;
username: string;
userProfileImage: string;
openToCollab: string;
tags: string[];
};
ProjectDataType is a custom one I have made.
type ProjectDataType = {
projectTitle: string;
thumbnail: string;
userName: string;
profileImage: string;
openToCollab: boolean;
tags: string[];
};
I am getting my error at the definition of handleCardClick.
CodePudding user response:
On ProjectDataType, you have openToCollab type as boolean
. On ProjectJSONData, you have openToCollab type as string
CodePudding user response:
This
projectTitle: {Project.projectTitle}
is not valid javascript or typescript syntax. The { } there don't do what you think they do.
You want this:
const handleCardClick = (Project: ProjectJSONData) => {
setSelectedProject({
projectTitle: Project.projectTitle,
thumbnail: Project.ProjectThumbnail,
userName: Project.username,
profileImage: Project.userProfileImage,
openToCollab: Project.openToCollab,
tags: Project.tags,
})
};
Additionally, openToCollab is string in one type, and boolean in the other.
And lastly, you use Project.projectThumbnail but the type has that declared with a capital P, so you must use Project.ProjectThumbnail.
With those changes, everything works fine.
