I am trying to learn typescript and to be quite honest I am having a hell of a time wrapping my head around this. I understand that this question has been asked COUNTLESS times before but I cannot for the life of me figure out how to translate the answers that I'm reading to my own code. Something which doesn't help is a lot of the answers I seem to find use a different syntax to write components than I have been using. Anyways any help is GREATLY appreciated because I am completely lost here. I have literally only two files, App.tsx and DisplayPerson.tsx
Inside my App.tsx file I have this code:
import React from 'react';
import DisplayPerson from './components/DisplayPerson';
export interface Person {
firstName: string;
lastName: string;
}
function App() {
const person1: Person = {
firstName: 'fname',
lastName: 'lname',
};
return (
<div>
<DisplayPerson person={person1} />
</div>
);
}
export default App;
And inside my DisplayPerson.tsx file I have:
import React from 'react';
import { Person } from '../App';
export default function DisplayPerson({ person }: Person) {
return (
<div>
<h1>person.firstName</h1>
<h1>person.lastName</h1>
</div>
);
}
In DisplayPerson.tsx I have an error which says "Property 'person' does not exist on type 'Person'". I tried to fix this by changing my Person interface to:
export interface Person {
person : {
firstName: string;
lastName: string;
}
}
And the declaration of my person1 const to this:
const person1: Person = {
person: {
firstName: 'fname',
lastName: 'lname',
},
};
Which did solve the error in DisplayPerson.tsx, however I now have an error in App.tsx which says "Type 'Person' is missing the following properties from type '{ firstName: string; lastName: string;}': firstName, lastName. The expected type comes from property 'person' which was declared here on type 'IntrinsicAttributes & Person"
This is when I tried googling my issue and frankly I just cannot figure out what's wrong even without googling. Any help is greatly appreciated and if you could also explain why what I've done does not work I would love that a lot.
Thank you so much!
You need to correct your props part. So your DisplayPerson.tsx
file will be like this
import React from 'react';
import { Person } from '../App';
interface IProps {
person: Person
}
export default function DisplayPerson({ person }: IProps) {
return (
<div>
<h1>{person.firstName}</h1>
<h1>{person.lastName}</h1>
</div>
);
}
In React, the structure is like below for Functional component
function DisplayPerson(props) {}
as you see here props
is a parameter that is of type object
. so you need to pass an object
. Now you want a person
as a key
inside that object which is Object deconstruction.
That's why it has to be done like #1 from the answer of Nathan.
You can refer this: https://javascript.info/destructuring-assignment#object-destructuring