前面笔记了那麽多,终於来实作看看了~先来做个简单的 to do app,也会纪录实作上遇到的问题。
若有错误,欢迎留言指教,感恩的心。
使用 create-react-app
来建置环境:
npx create-react-app my-app --template typescript
# or
yarn create react-app my-app --template typescript
cd my-app
npm start
# or
yarn start
打开 http://localhost:3000/ 看到 react logo, 就启动成功。
安装 TypeScript 添加到现有的 Create React App 项目
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
# or
yarn add typescript @types/node @types/react @types/react-dom @types/jest
cd src
rm App.css App.test.tsx index.css logo.svg serviceWorker.ts setupTests.ts
src/index.tsx
中将一些没用的进行移除整理。
//@file: src/index.tsx
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);
src/App.tsx
const App = () => {
return <>hello world</>;
};
export default App;
整理後,看看有没有印出 hello world
。
就按习惯安装会用到的套件,记得也要安装 TypeScript 支援版本,没安装的话,import 时就会报错,我也是被报错才知道原来还要安装 ts 版。
yarn add --dev styled-components @types/styled-components bootstrap react-bootstrap uuid @types/uuid
*.d.ts
一般来说,ts 会解析专案中所有的 *.ts 档案,当然也包含以 .d.ts 结尾的档案。所以当我们将 type.d.ts 放到专案中时,其他所有 *.ts 档案就都可以获得 type 的型别定义了,可以全域使用。
新增 src/types.d.ts
, 并将定义的 interface 写进去,供全域使用。
//@file: src/types.d.ts
//定义Todo介面, 会有text, 及complete是否完成
interface Todo {
text: string;
complete: boolean;
}
//定义IAddTodo , 回传参数text为string型别, 并无回传值void
type AddTodo = (text: string) => void;
//定义ToggleTodo, 回传参数index为number型别, 并无回传值void (点击todo改变complete状态用)
type ToggleTodo = (index: number) => void;
//定义DeleteTodo , 回传参数index为number型别, 并无回传值void (删除todo用)
type DeleteTodo = (index: number) => void;
当然上面定义的我也是边写有需要再定义,也可以使用interface
去定义,特别注意 interface 及 type 定义 function 的写法不一样唷:
//interface
interface IAddTodo {
(text: string): void;
}
//type
type IAddTodo = (index: number) => void;
我遇到的一些事:
过程中犹豫要用 interface
或是 type
,问了几个大大的公司,有用 interface
也有用 type
的, 使用 type
的多一点,原因似乎都是公司这样用就这样用了,或是习惯。
原本想用 type 了, 因为觉得 type 可以描述 primitive type、tuple、union type 等(可看之前写的),interface 无法,为了後续维护及扩充,比较方便。
但看的 todo app参考文章 定义object时使用 interface
,定义 function 使用type
。 然後也看了这篇文 :
我後来也这样使用了。
我一开始是参考这篇,他会一个步骤一个步骤教,对新手来说蛮友善的,提供有需要的朋友。後来我自己新增减少修改一些,我这边笔记是已完成版及实作过程中遇到的问题,真心佩服一步一步教学的大大们。
明天来继续 part 2~
https://create-react-app.dev/docs/adding-typescript/
https://typeofnan.dev/your-first-react-typescript-project-todo-app/
https://willh.gitbook.io/typescript-tutorial/basics/declaration-files
<<: 【29】遇到不平衡资料(Imbalanced Data) 时 使用 SMOTE 解决实验
>>: [Day 29] -『 GO语言学习笔记』- 复合型别 - 切片(Slice) (I)
今天的目标 要怎麽简单快速地做出客制化地文件?今天,我们会教用 GAS 搭配 Goolge Doc。...
有意义的讨论 层层拆解,找到歧异点 讨论过程里面,我们通常容易跳到结论做为起点,而我们通常也会先看到...
堆叠(Stack)是一种排列结构,不过是由下往上堆放,任何动作都必须从最顶端(top)进行,因此有「...
tags: OC 30 day OC 有哪些数据类型呢? oc 中支援所有C语言的数据变量。 基本数...
早上起来,决定至少去吸食一下咖啡,买个包子,看看时间已经八点半,出发。 顺着中华路走到中山路,然後拐...