typescript 在React/NextJS应用程序中有正确的导出/导入类型的方法吗

6pp0gazn  于 2023-03-24  发布在  TypeScript
关注(0)|答案(1)|浏览(104)

我想使用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,然后重用它。

mum43rcc

mum43rcc1#

// pages/users.tsx
export type Post = {...};

// pages/user.tsx
import { Post } from './users';

相关问题