本笔记为下面视频的笔记

【1个项目学会TypeScript核心基础语法】 https://www.bilibili.com/video/BV12P411E79E/

TypeScript安装

TypeScript是JavaScript的超集,为JavaScript新增了许多新的特性。

TypeScript并不能在浏览器中直接执行,因此跟JavaScript不同的是,我们需要安装一个编译器去将TypeScript转换成JavaScript

1
npm install -g typescript //全局安装

安装完成后我们可以通过命令来检查我们的安装情况

1
2
❯ tsc -v
Version 5.0.2

接着我们在项目文件夹下使用终端

1
2
3
4
5
6
7
8
9
10
11
12
13
❯ tsc --init

Created a new tsconfig.json with:
TS
target: es2016
module: commonjs
strict: true
esModuleInterop: true
skipLibCheck: true
forceConsistentCasingInFileNames: true


You can learn more at https://aka.ms/tsconfig

我们就初始化了一个配置文件,在里面可以看到target键值对,它的含义是会将我们的ts文件按照es2016的方式编译成js。

为了不必要每次都进行一次编译指令,我们可以用到tsc -w进行自动编译。

变量声明

typescript之所以为type,正是因为TS对类型有了类型检查,这可以使得我们更方便的检查出我们一些不容易在JavaScript开发时检查到的类型错误

1
let name: string = 'icewindy'

在变量名后面使用冒号+类型就可以对我们的类型进行标注了。

在实际使用中,TS会自动帮我们推断变量的类型,因此省去类型标注也是可以的。

断言与联合

现在我们想获取到页面的按钮元素,我们使用document.querySelector('button')获取到,但是我们发现编译器给我们报错了,因此ts会提醒我们button这个值可能为空。

想解决这个问题我们可以用断言来解决,写法就是在末尾加类型即可,意思是明确告诉编译器,这个按钮确实存在

1
const button = document.querySelector('button') as HTMLButtonElement;

但是为了出现别的情况,我们可以使用TypeScript中的联合类型,也就是使用 | 连接两个类型

1
const button: HTMLButtonElement | null = document.querySelector('button');

接口与实现

现在我们需要实现一个猫类,由于可能有多种猫,因此我们这里可以构造一个CatType接口

1
2
3
4
5
6
7
interface CatType {
id: string;
url: string;
height: number;
width: number;
test?: boolean; //在变量名后加?表示这个变量可有可无
}

接着我们就可以去实现这个类,实现的方法与Java非常相似

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Cat implements CatType {

id: string;
url: string;
height: number;
width: number;

//构造函数
constructor(id: string, url: string, height: number, width: number) {
this.id = id;
this.url = url;
this.height = height;
this.width = width;
}
}

修饰符与函数类型

当我们想让某个类里面的方法或者元素,对所有人都可访问时,我们可以使用public对它进行修饰。

例如我们现在需要一个方法在WebDisplay类里,接受API传回来的数据,并且使数据追加到表格后,然后使它在整个网页都可用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class WebDisplay {
public static addData(data: CatType): void {
const cat: Cat = new Cat(data.id, data.url, data.height, data.width);
const tableRow: HTMLTableRowElement = document.createElement('tr');
tableRow.innerHTML = `
<td>${cat.id}</td>
<td><img src="${cat.url}" /></td>
<td>${cat.height.toString()}</td> <!--为了使数值能在页面中显示需要toString()-->
<td>${cat.width.toString()}</td>
<td>${cat.url}</td>
<td><a href="#">X</a></td>
`;
tableBody?.appendChild(tableRow);//?表示如果为null就不添加子元素
}
}

我们可以看到我们对这个方法进行了类型标注,这个类型标注表示我们这个函数的返回值类型。

数组

一般而言,对数组进行类型标注是标注数组内数据的类型

1
let numArr: number[] = [1,2,3]

如果我们需要在数组内放对象,我们会通过编写一个接口,把对象的类型写在接口内

1
2
interface Cat {}
let ObjArr:Cat[] = [{}]

事件监听

现在我们需要监听button点击事件,以触发我们的新增函数,我们直接用到addEventListener即可

1
button?/*与前面加?原因一致*/.addEventListener('click', getData)

我们可以在监听事件处注明事件类型,以便于我们检查我们的事件是否有错误,即使用尖括号在事件再标注一次事件类型

1
button?.addEventListener<'click'>('click', getData);