Next.js应用转换为TypeScript方法demo

作者:Jovie 时间:2024-05-11 09:36:17 

引言

如果你不确定TypeScript是什么,它基本上是一种建立在JavaScript之上的类型化语言。所有的JavaScript都是有效的TypeScript,但反之亦然。你可以在这里阅读更多关于它的信息,以及它如何与React/Next.js一起工作。你可以在你的项目中轻松地设置TypeScript,只需几个命令和一些小的重构,在这篇文章中,我将告诉你如何做!

添加TypeScript

最初添加TypeScript到你的Next.js项目很简单。只需通过运行以下命令来安装TypeScript。

npm install --save-dev typescript @types/react @types/node

然后,在你的项目根部创建一个空的 tsconfig.json文件,然后在你的项目的根部创建一个空的你可以手动完成,或者在你的项目根部运行以下命令。

touch tsconfig.json

然后使用 "npm run dev "启动你的项目,你应该在控制台中看到以下一行。

Next.js应用转换为TypeScript方法demo

Next.js会在你的 tsconfig.json文件中加入一些预选的选项。我推荐的一个选项是在第11行将strict设置为true,以启用TypeScript的一些更严格的打字选项,但并不是必须的。

重构

你会发现你的项目仍然运行良好,这是因为你所有的.js或.jsx文件仍然是JavaScript。要将它们切换到TypeScript,只需将文件扩展名改为.ts或.tsx。

你现在可能又会遇到一些错误,所以我将讨论一些常见的错误。这里有一个JavaScript组件的例子,它使用API调用检索一些有趣的事实,并使用SSR渲染它们。这个组件使用的是TailwindCSS的样式,我强烈建议你看一下它。

import React, { useState } from 'react';
import axios from 'axios';
function fetchFact() {
   //Just a simple get request which gets back a fact in a JSON object
   return axios
       .get('https://uselessfacts.jsph.pl//random.json?language=en')
       .then((res) => {
           return res.data;
       });
}
//TS7031: Binding element 'facts' implicitly has an 'any' type.
export default function SSRExample({ facts }) {
   return (
       <div className="flex h-screen w-screen flex-col items-center justify-center bg-white text-3xl text-white">
           <p className="mb-10 rounded bg-neutral-800 p-10">
               Heres some fun facts!
           </p>
           <ul className="flex max-w-2xl flex-col gap-5 rounded bg-neutral-800 p-10 shadow">
               {
                   //TS7031: Binding element 'id' implicitly has an 'any' type.
                   //TS7031: Binding element 'text' implicitly has an 'any' type.
                   facts.map(({ id, text }) => (
                       <li key={id}>{text}</li>
                   ))
               }
           </ul>
       </div>
   );
}
//TS7031: Binding element 'query' implicitly has an 'any' type.
export async function getServerSideProps({ query }) {
   const { count } = query;
   const promises = [...new Array(Number(count))].map(() => fetchFact());
   const facts = await Promise.all(promises);
   return {
       props: {
           facts,
       },
   };
}

输入道具

我在这个组件中得到的第一个错误是,TypeScript不知道我的道具是什么类型。这在严格模式下会导致一个错误,因为我们不允许使用任何道具。为了解决这个问题,我只需要为我的道具添加一个类型。

type Fact = {
   id: string;
   text: string;
};
type SSRExampleProps = {
   facts: Fact[];
};
//TS7031: Binding element 'facts' implicitly has an 'any' type.
export default function SSRExample({ facts }: SSRExampleProps) { ... }

现在,来自初始道具的错误,以及试图映射事实数组的错误都消失了。

需要注意的一件事是,我们在这里使用了对象重构,这可能会掩盖props是一个函数参数的事实。你的props将永远是一个包含你提供的任何props的对象,而不是直接参数。

export default function SSRExample({ facts }: { facts: { id: string; text: string }[]})
export default function SSRExample(facts: { id: string; text: string }[])

GetXProps

这段代码中的另一个问题是,我们的"getServerSideProps()"函数不知道它的参数是什么。如果你对这个函数不熟悉,请查看我们这里的文章,了解服务器端渲染的介绍。如果你使用getStaticProps或getStaticPaths,情况也会一样。

为了解决这个问题,Next.js为每一种和它们的参数提供了类型。需要注意的一点是,这些类型是针对箭头函数的,所以如果你使用的是正常的函数体,你就必须重构你的函数。

下面是我们更新的 getServerSideProps():

export const getServerSideProps: GetServerSideProps = async ({ query }) => {
   const { count } = query;
   const promises = [...new Array(Number(count))].map(() => fetchFact());
   const facts = await Promise.all(promises);
   return {
       props: {
           facts,
       },
   };
};

还有一个小细节是,我们的 ***fetchFact()***函数没有一个类型。在Next.js函数的交互方式下,这并没有造成任何问题,但如果我希望在其他地方使用该函数,就会遇到问题。由于我们已经为这个事实做了类型,重构这个事实很简单。

function fetchFact(): Promise<Fact> {
   //Just a simple get request which gets back a fact in a JSON object
   return axios
       .get('https://uselessfacts.jsph.pl//random.json?language=en')
       .then((res) => {
           return res.data;
       });
}

状态

将类型添加到一个 ***useState()***钩子添加类型可以通过向函数提供一个类型参数来完成。我对前面的例子进行了重构,只允许点击一个按钮来获取一个额外的事实,并将这些额外的事实存储在状态中。

export default function SSRExample({ facts }: SSRExampleProps) {
   const [extraFacts, setExtraFacts] = useState<Fact[]>([]);
   const getAnotherFact = () => {
       fetchFact().then((fact) => {
           setExtraFacts((oldValue) => [...oldValue, fact]);
       });
   };
   return (
       <div className="flex h-screen w-screen flex-col items-center justify-center bg-white text-3xl text-white">
           <p className="mb-10 rounded bg-neutral-800 p-10">
               Heres some fun facts!
           </p>
           <ul className="flex max-w-2xl flex-col gap-5 rounded bg-neutral-800 p-10 shadow">
               {
                   //TS7031: Binding element 'id' implicitly has an 'any' type.
                   //TS7031: Binding element 'text' implicitly has an 'any' type.
                   [...facts, ...extraFacts].map(({ id, text }) => (
                       <li key={id}>{text}</li>
                   ))
               }
               <li>
                   <button
                       className="rounded bg-neutral-900 p-5 shadow"
                       onClick={() => getAnotherFact()}>
                       More
                   </button>
               </li>
           </ul>
       </div>
   );
}

TypeScript会尽力从你的状态初始值中推断出类型,但对于像这个事实数组这样更复杂的例子,我们必须包括类型参数。

希望这些例子足以帮助你在Next.js项目中开始使用TypeScript。TypeScript是一种非常有用的语言,可以帮助你写出更干净、更正确的代码,更多关于Next.js转换为TypeScript的资料请关注脚本之家其它相关文章!

来源:https://juejin.cn/post/7176279211399708732

标签:Next.js,TypeScript,Next
0
投稿

猜你喜欢

  • JS数组方法汇总

    2009-08-03 14:06:00
  • pip/anaconda修改镜像源,加快python模块安装速度的操作

    2022-06-01 10:42:26
  • 解决PHP 7编译安装错误:cannot stat ‘phar.phar’: No such file or directory

    2023-09-05 06:07:44
  • MySQL使用select语句查询指定表中指定列(字段)的数据

    2024-01-26 07:51:49
  • css去掉checkbox边框的方法

    2011-06-06 10:32:00
  • centos7 PHP环境搭建 GD库 等插件安装方法

    2023-11-05 21:25:38
  • perl 调试命令的相关知识小结

    2022-10-01 14:09:48
  • python的Crypto模块实现AES加密实例代码

    2022-10-02 17:43:10
  • 基于node打包可执行文件工具_Pkg使用心得分享

    2024-05-08 09:37:47
  • 基于OpenCV(python)的实现文本分割之垂直投影法

    2023-11-17 08:45:39
  • python 装饰器的实际作用有哪些

    2023-04-10 15:00:50
  • sqlserver 数据库学习笔记

    2011-12-01 08:15:06
  • python3下实现搜狗AI API的代码示例

    2022-04-11 09:30:58
  • 一文详解typeScript的extends关键字

    2024-02-24 11:30:02
  • ​​​​​​​如何利用python破解zip加密文件

    2022-11-27 17:51:30
  • Python3直接爬取图片URL并保存示例

    2022-10-31 17:30:40
  • VSCode必装Go语言以下插件的思路详解

    2024-04-30 09:53:42
  • Python金融数据可视化汇总

    2023-04-12 21:27:41
  • 详解Python中的Cookie模块使用

    2023-01-02 21:30:39
  • python flask中静态文件的管理方法

    2022-12-11 01:32:40
  • asp之家 网络编程 m.aspxhome.com