TypeScript学习
TypeScript 学习
安装TypeScript
全局安装TypeScript
:
1 | yarn global add typescript |
全局安装ts-node
,用于快速编译 ts 文件:
1 | yarn global add ts-node |
静态类型的理解
定义变量时,首先定义其类型,在后续的使用中,也只能用这种类型的数据赋值给变量。
基础类型
基础类型也可以叫做原始类型,与 JavaScript 中的原始类型类似。typescript 中的原始类型有:
- 布尔值
- 数字
- 字符串
- Null
- Undefined
- Symbol
- BigInt
其中,Symbol
和BigInt
为 ES6 中新增的基础类型。
1 | const isTure: Boolean = false |
除了上述类型,typescript 中还有一个空值void
,在函数中,可以表示没有任何返回值:
1 | function func(): void { |
undefined
与null
类型是所有类型的子类型,也就是说,定义变量时可以将初始值赋值为undefined
与null
,而void
就不行。
1 | let count: number = undefined |
对象类型
在 typescript 中,使用接口interface
来定义对象的类型。
1 | interface People { |
接口定义的值,在使用中是不可以出现缺少或者多余的字段名:
1 | interface People { |
若是需要一个可选的属性,只需在字段名后面加一个问号?
,但是使用时,同样不可以出现多余属性:
1 | interface People { |
类型注解和类型推断
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Comment