CodeMan

Each of us must find a way to love the world. You have found yours.

0%

第一个Typescript应用

环境配置

1. 安装NODE.JS

NOJE.JS: https://nodejs.org/en/

1
2
3
4
5
6
➜  ~ node --version
v15.4.0

➜ ~ npm --version
7.0.15

2. 安装GIT

GIT: https://git-scm.com/downloads

1
2
3
4

➜ ~ git --version
git version 2.28.0

3. 安装TYPESCRIPT
1
2
3
4
5
npm install --global typescript@4.2.2

➜ ~ tsc --version
Version 4.2.2

4. 安装VSCode

VS Code: https://code.visualstudio.com

创建项目

1.初始化项目
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
➜  typescript mkdir todo
➜ typescript cd todo
➜ todo npm init --yes
Wrote to /Users/yangandrew/work/typescript/todo/package.json:

{
"name": "todo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}

2. 创建项目结构以及tsconfig.json

tsconfig.json

1
2
3
4
5
6
7
8
9
{
"compilerOptions": {
"target": "es2018",
"outDir": "./dist",
"rootDir": "./src",
"module": "commonjs"
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
 
➜ todo mkdir dist
➜ todo mkdir src
➜ todo touch tsconfig.json
➜ todo vi tsconfig.json
➜ todo tree
.
├── dist
├── package.json
├── src
└── tsconfig.json


3. src目录下创建index.ts
1
2
3
4

console.clear();
console.log("你好,Typescript");

项目目录下编译

1
2
3
4
5
6
7
8
9
10
11
➜  todo tsc

➜ todo tree
.
├── dist
│   └── index.js
├── package.json
├── src
│   └── index.ts
└── tsconfig.json

不要去修改dist下面的js文件。它们都是由typescript编译出来的文件。

使用node运行

1
2
3
4
5
➜  todo node dist/index.js

➜ todo node dist/index.js
你好,Typescript

3. 定义数据模型

Todo需求:

  • 查年Ttem
  • 添加Ttem
  • 标记为完成
  • 查询Item

添加todoItems.ts到src目录
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export class TodoItem {
public id: number;
public task: string;
public complete: boolean = false;
public constructor(id: number, task: string, complete: boolean = false) {
this.id = id;
this.task = task;
this.complete = complete;
}
public printDetails() : void {
console.log(`${this.id}\t${this.task} ${this.complete
? "\t(complete)": ""}`);
}
}