I'm trying to pass an object via props and having an issue understanding what Typescript wants.
Do I create an interface for Props than a separate interface for the properties within the object?
What I have:
import React from 'react';
interface Props {
link: object;
}
interface link {
description: string;
url: string;
}
const Link = (props: Props) => {
const { link } = props;
return (
<div>
<div>
{ link.description }({ link.url })
</div>
</div>
);
};
export default Link;
Errors I'm getting:
Property 'description' does not exist on type 'object'. TS2339
Property 'url' does not exist on type 'object'. TS2339
CodePudding user response:
object
is never a good way to type things in TS, as you can't retrieve any information from the object (its properties and much less its properties' types). Also, you're not using this link
interface that you're creating! You need to use it to type your props:
interface Link {
description: string;
url: string;
}
interface Props {
link: Link;
}
CodePudding user response:
use it like this, because Typescript can't detect that if the object has property or not:
interface Props {
link: {
description: string;
url: string;
};
}
const Link = (props: Props) => {
const { link } = props;
return (
<div>
<div>
{link.description}({link.url})
</div>
</div>
);
};
export default Link;