在React/Next应用程序中,使用TypeScript保存类型应该放在哪里?

huangapple go评论66阅读模式
英文:

Where to save types in a React/Next application using TypeScript?

问题

我正在创建一个类似这样的 Next.js 页面:

const Index: NextPage<PageProps> = (props) => {
// 其他代码在这里...

在此之前,我像这样定义了我的 PageProps:

type PageProps = {
    pictures: pictures[]
};

现在我需要定义图片类型,但考虑到我还想从其他页面使用它,我希望将它放在一个外部文件中。

如何在外部文件中定义类型并在我的页面中引用它?

英文:

I am creating a Next.js page like this

const Index: NextPage&lt;PageProps&gt; = (props) =&gt; {
// other code here...

Before this I defined my PageProps like this:

type PageProps = {
    pictures: pictures[]
};

Now I'd need to define the picture type, but given that I want to use it from other pages as well, I would like to have it in an external file.

How can I define the type in an external file and reference it in my page?

答案1

得分: 1

你可以从一个单独的文件中导出 PageProps,然后在你的 Next.js 页面中导入它:

// types.ts
export type PageProps = {
  pictures: pictures[]
}
// page.tsx
import type { PageProps } from '../types.ts' // 用正确的相对路径替换到你的 `types.ts` 文件

const Index: NextPage<PageProps> = (props) => {
// 其他代码在这里...
英文:

You can export PageProps from a separate file and import it in your Next.js page:

// types.ts
export type PageProps = {
  pictures: pictures[]
}
// page.tsx
import type { PageProps } from &#39;../types.ts&#39; // replace with the correct relative path to your `types.ts` file

const Index: NextPage&lt;PageProps&gt; = (props) =&gt; {
// other code here...

huangapple
  • 本文由 发表于 2023年1月8日 23:03:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048818.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定