在 NextJS Typescript 项目的功能组件中向 props 添加类型的更好方法

Jer*_*yal 4 typescript reactjs next.js

我想在有多个道具时添加类型。例如:

export default function Posts({ source, frontMatter }) {
...
}
Run Code Online (Sandbox Code Playgroud)

我发现的一种方法是首先创建包装类型,然后创建参数类型。例如:

type Props = {
  source: string;
  frontMatter: FrontMatter;
};

type FrontMatter = {
  title: string;
  author: string;
  date: string;
};


export default function Posts({ source, frontMatter }:Props) {
...
}
Run Code Online (Sandbox Code Playgroud)

但是有没有办法避免这种额外的Props类型,因为我只将其用于此功能。我希望能够实现这样的目标:

export default function Posts({ source:string, frontMatter:FrontMatter }) {...}
Run Code Online (Sandbox Code Playgroud)

b3h*_*r4d 6

我认为这是你个人的决定,你的第一个解决方案是正确的,如果它工作正常你可以使用它,我更喜欢使用这样的东西:

interface PostProps {
  source: string;
  frontMatter: {
    title: string;
    author: string;
    date: string;
  }
}

export const Posts: React.FC<PostProps> = ({source,frontMatter}) => {
...
}
Run Code Online (Sandbox Code Playgroud)

您建议的方式也可以是这样的:

export default function Posts({source,frontMatter}:{source: string,frontMatter:FrontMatter}) {
...
}
Run Code Online (Sandbox Code Playgroud)