I want to add types when there are multiple props. For ex:
export default function Posts({ source, frontMatter }) {
...
}
One way I found is to first create wrapper type and then create parameter type. For ex:
type Props = {
source: string;
frontMatter: FrontMatter;
};
type FrontMatter = {
title: string;
author: string;
date: string;
};
export default function Posts({ source, frontMatter }:Props) {
...
}
But is there a way to avoid that extra Props
type because I'm using that for only this function. I'm hoping to achieve something like this:
export default function Posts({ source:string, frontMatter:FrontMatter }) {...}
i think its ur personal decision,ur first solution is true and if it works fine u can use it, i prefer using somthing like this:
interface PostProps {
source: string;
frontMatter: {
title: string;
author: string;
date: string;
}
}
export const Posts: React.FC<PostProps> = ({source,frontMatter}) => {
...
}
also ur suggested way can be like this:
export default function Posts({source,frontMatter}:{source: string,frontMatter:FrontMatter}) {
...
}
You can define the interface like below:-
interface PostConfig {
source: string;
frontMatter: FrontMatterConfig;
}
interface FrontMatterConfig {
title: string;
author: string;
date: string;
}
And also mention the typing for the component:-
const Posts: FunctionComponent<PostConfig> = ({
source,
frontMatter: { title, author, date }
}) => {
return (
<div>
<b>{source}</b>
<div>{title}</div>
<div>{author}</div>
<div>{date}</div>
</div>
);
};
Sample Code:- https://codesandbox.io/s/reverent-dijkstra-t4sfc?file=/src/App.tsx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.