我想使用API响应的类型,我想知道是否有方法导出和导入这些类型
// pages/users.tsx
type Post = {
id: number;
name: string;
username: string;
email: string;
address: {
street: string;
suite: string;
city: string;
zipcode: string;
geo: {
lat: string;
lng: string;
};
};
phone: string;
website: string;
company: {
name: string;
catchPhrase: string;
bs: string;
};
};
export const getStaticProps: GetStaticProps<{
posts: Post[];
}> = async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
const posts: Post[] = await res.json();
return {
props: {
posts,
},
};
};
const users: React.FC<
InferGetStaticPropsType<typeof getStaticProps> & Props
> = ({ posts, isLogged }): JSX.Element => {
return (
<div>
<User posts={posts} />
</div>
);
};
export default users;
我想重新使用Post
的类型
// pages/user.tsx
import { FC } from "react";
type Props = {
posts: Post[]; // cannot find name 'Post'
};
const User: FC<Props> = ({ posts }) => {
return (
<div>
{posts.map(
({
name,
id,
company: { name: CompanyName, catchPhrase },
address: { city, zipcode },
}) => {
console.log(CompanyName);
return <h1 key={id}>City: {city}</h1>;
}
)}
</div>
);
};
export default User;
那么如何以正确的方式导出和导入类型,我应该在全局项目结构中创建type
文件夹吗?或者只是在每个文件夹上创建一个types.ts
,然后重用它。
1条答案
按热度按时间mum43rcc1#