Reputation: 1277
I am getting the error which I'm sure is due to typescript. This is an example that I am trying to get to work. I use js server to import a few notes. The error is a red line under the {note} in the NoteCard.tsx file. Can someone please help me understand how to using these properties.
here is my notecard.tsx
export default function NoteCard({ note }) { return <div>{note.title}</div>;}
here is my notes.tsx
export default function Notes() {
const [notes, setNotes] = useState<any[]>([]);
useEffect(() => {
fetch("http://localhost:8000/notes")
.then((res) => res.json())
.then((data) => setNotes(data));
}, []);
return (
<Container>
<Grid container>
{notes.map((note) => (
<Grid item key={note.id} xs={4} md={4} lg={4}>
<NoteCard note={note} />
{/* <Paper>{note.title}</Paper> */}
</Grid>
))}
</Grid>
</Container>
);
}
Upvotes: 2
Views: 8465
Reputation: 414
My other answer explains how to eliminate the linter-warning. However, it does not address the underlying issues with the code. One of the main benefits of using TypeScript, is that it's statically typed with the help of types. The type any is the highest type, similar to Object in Java; all types are a sub-type of any. The any-type should be avoided when possible, as you're practically using dynamic typing again; this means that you're more or less back to using plain JavaScript.
Just for completness sake, I'll add a snippet showing how I would write such a component.
export type Note = {
title: string
}
export default function NoteCard({note}: {note: Note}) {
return <>{note.title}</>
}
export default function Notes() {
const [notes, setNotes] = useState<Note[]>([])
// Rest of Notes.tsx
}
Upvotes: 0
Reputation: 414
The implicit wording is not a coincidence. You can simply type the function, and give it an explicit type.
export default function NoteCard({ note }: { note: any }) { return <div>{note.title}</div>;}
This should fix the warning.
Upvotes: 9
Reputation: 107
Try adding a props interface to the NoteCard function
interface NoteCardProps {
note: {
title: string
}
}
export default function NoteCard({ note }: NoteCardProps) { return <div>{note.title}</div>;}
Upvotes: 2