Trying to learn some Typescript and have encountered an error early. I'm getting quite a few errors although I'm following a tutorial. I have commented out the errors I'm receiving. If someone could please explain why they are occurring, and how to fix them that would be fantastic.
import React from "react";
interface IProps {
name: string;
age: number;
title: string;
}
let Customer: React.FC<IProps> = ({
name: string,
//'string' is declared but its value is never read.
age: number,
title: string,
//'string' is declared but its value is never read.
}) => {
return (
<React.Fragment>
<h2>Customer Component</h2>
<ul className="list-group">
<li className="list-group-item">Name: {name}</li>
{/* //This JSX tag's 'children' prop expects a single child of type 'ReactNode', but multiple children were provided.ts(2746) */}
{/* 'name' is deprecated.ts(6385) */}
{/* lib.dom.d.ts(17329, 5): The declaration was marked as deprecated here. */}
<li className="list-group-item">Age: {age}</li>
{/* Cannot find name 'age'. */}
<li className="list-group-item">Title: {title}</li>
{/* Cannot find name 'title'. */}
</ul>
</React.Fragment>
);
};
export default Customer;
CodePudding user response:
let Customer: React.FC<IProps> = ({
name: string,
//'string' is declared but its value is never read.
age: number,
title: string,
//'string' is declared but its value is never read.
}) => {
IProps
is the interface where you define all your properties with specific types. Right side you use that as a variable. You're destructing the object so just define the names like {name, age, title}
.
If you use name: string
on the right side, you renamed the name
as string
. The field name
is taking from libraries that is why you got that error. On the second line, there is no age
variable as you renamed it to number
.
This is the updated code.
import React from "react";
interface IProps {
name: string;
age: number;
title: string;
}
let Customer: React.FC<IProps> = ({
name,
age,
title,
}) => {
return (
<React.Fragment>
<h2>Customer Component</h2>
<ul className="list-group">
<li className="list-group-item">Name: {name}</li>
<li className="list-group-item">Age: {age}</li>
<li className="list-group-item">Title: {title}</li>
</ul>
</React.Fragment>
);
};
export default Customer;
You can read Object Destructuring assignment and renaming the destructured fields