这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战
基本类型
学习基本类型
小乐,你环境搭建好了没?
搭建好了,我把基本类型都看完了。
这么快,感觉怎么样
TS 真的很好用,类型系统很强大,它为声明了类型的变量,提供了静态检查机制,编程效率提升不少。
这么厉害,那我也赶紧学习下 TS 的基本类型。
基本类型
Primitive 原始数据类型
- boolean 布尔值
- string 字符串
- number 数字
- null
- undefined
- Symbol ECMAScript 2015 中的新类型
现在我们来看简单的例子:
注:类型是小写字母开头的。Boolean 代表的是 JS 中的构造函数,boolean 代表是的 TS 的基本数据类型
let isMale: boolean = true;
let myName: string = 'Alex';
let myAge: number = 20;
let myGirlfriend: null = null;
let myHouse: undefined = undefined;
习题:为下面变量声明合适的类型
const animal:_____ = 'panda';
const weight:_____ = 10;
const isMammal:_____ = true;
const wing:_____ = null;
const swim:_____ = undefined;
答案:
本题比较简单,都是 js 最基本的数据类型。
const animal: string = 'panda';
const weight: number = 10;
const isMammal: boolean = true;
const wing: null = null;
const swim: undefined = undefined;
类型推论 - 基本
每定义一个变量,都需要使用 : + 类型的方式,来定义出它的类型。那么有没有更简单更智能的方式呢?
将鼠标移动到对应的变量,可以看到它可以正常识别出变量的类型。这样就是通过类型声明,识别出来的
如果我们把类型声明全部去掉的话,然后再把鼠标移动到变量上,可以看到它还是可以正确识别这个变量的类型,这里就是通过赋值语句,推论出来的类型。
如果我们定义一个变量没有给它赋值,再后面再给他赋值的话,那么这个变量,会被推论成 any 类型。
下面来总结一下:
- 定义时未赋值,就会推论成 any 类型
- 定义时赋值就能利用到类型推论
// 定义时未赋值,就会推论成 any 类型
let isMale;
isMale = true;
// 定义时赋值就能利用到类型推论
let myName = 'Alex';
let myAge = 20;
let myGirlfriend = null;
let myHouse = undefined;
类型推论可以帮助我们省略掉很多冗余的代码,所以我们应该竭尽所能的依赖类型推论,后面的章节还会介绍更加智能的类型推论。
习题:严格类型模式下,变量 animal 的类型为?
let animal;
animal = 10;
animal = 'panda';
animal = null;
选项
A. number
B. string
C. null
D. any
答案:选 D
let animal;
在声明阶段未对变量进行赋值操作,变量 animal 会被推论为 any。后面的操作不会影响变量 animal 的类型。