一、介绍 TypeScript
1. TypeScript 是什么
TypeScript
是一款用来检查 Javascript 数据类型的工具语言。
2. TypeScript 有什么用
帮助开发者在代码编译成 JavaScript 前检测数据类型是否正确,如果不正确则给出相应的 error
提示,有助于开发效率和代码的稳定性。
3. tsconfig.json 配置文件
每个项目在使用 Typescript
时,根目录都会生成一个 tsconfig.json
文件,这个文件可以用来告诉 TypeScript
在编译器期间时使用什么样的规则去进行检测,下面是默认配置:
{
"compilerOptions": {
"baseUrl": ".", // 告诉 TS 当前环境上下文
"target": "es6", // 编译后的 js 代码为 ES6 语法
"module": "esnext", // 让 TS 识别 ES6 代码
"strictNullChecks": true, // 变量赋空值时要么是 `undefined` 或 `null`
// 当使用缩写引入组件时,TS 并不知道这个缩写的含义,
// 这里就可以通过 paths 来告诉 TS 使用 @/ 时 去 ./src/* 下找,避免 TS 乱报提示错误。
"paths": {
"@/*": ["./src/*"]
},
},
"include": ["/src*.ts"]// 指定要编译的文件目录
"exclude": ["test/*"], // 要忽略编译的文件目录,注意:它的路径环境是根据 include 的
}
TS 的配置选项有很多,这里就不一一演示了,有兴趣的自行查阅相关资料,
接下来我们开始进入正文。
二、正文
1. 定义数组
// 普通数组
let bestNumber: number[] = [100, 200] // 一维数组
let bestNumbers: number[][] = [[100, 200], [300, 400]] // 二维数组
// 使用扩展符形成数组
function getArs(...ars:string) { console.log(arr) }
getArs(['hello', 'world'])
2. 定义元组
元组也属于数组,不同的是它可以定义多种数据类型
,不过有一些地方需要注意,看代码:
// 元组,即数组里可以存放很多类型
let mixup: [string, number, string, boolean, object] = ['hello', 1, 'world', true, {}]
// 注意1:不能将数组赋给元组,哪怕定义的类型是相同的都会报错。
let mixup: [string, string] = ['A', 'B']
let arr: string[] = ['A', 'B']
mixup = arr // Error
// 注意2:元组定义后长度就是固定的,不可随意 push 或 [index] 赋值。
let mixup: [string, string] = ['A', 'B']
mixup[2] = 'C' // Error
mixup.puah('C'] // Error
3. 定义 enum(枚举)
enum
可以是 number/string
类型,默认是 number
类型,主要可以用来定义一些默认常量值,比如周期、订单状态、等
// 1. number 类型:默认从 0 开始,
// 即 South = 0, North = 1, East = 2, West = 3
enum Direction{
South,
North,
East,
West
}
let myDirection: Direction = Direction.South // 0
console.log(myDirection === Direction.South) // true
// 官方建议 enum 使用 string 类型,它比 number 更严格些,
// 因为 number 类型会有一些 ‘特殊’ 比如:
myDirection = 100 // 赋值后可以再次更改
// 2. string 类型
enum OrderStatus {
SUCCESS = "10000",
ERROR = "-10000",
SERVER_ERROR = "50000",
CLIENT_ERROR = "40000"
}
let code: OrderStatus = OrderStatus.SUCCESS
// 赋值后不能再更改,这便是与 number 的一个不同之处
code= "Hello" // Error
4. 定义 interface 接口
interface
一般就是给对象用的。
// 1. 接口用于普通对象
interface User {
name: string;
age: number;
}
let Jack:User = {name: 'Jack', age: 29}
// 2. 接口用于参数对象
function person(user: User ) {
console.log(user)
}
person({name: 'Tony', age: 10})
// 3. 接口用于数组嵌套对象
let arrForObject: User[] = [
{name: 'Tony', age: 12},
{name: 'Linda', age: 15}
]
5. 定义 type (别名)
type
可以节省重复定义数据类型,就跟声明变量一样,只不过关键字不是 let/const
而是 type
,有同学可能注意到这个跟 interface
挺像的,有什么区别呢?这里我就简单解释下:
- type 不支持 extends/implements ,interface 支持
- type 不支持接口合并,interface 支持
- interface 不支持
&
交叉类型, type 支持 - interface 不支持直接定义
string/number
普通类型,必须用{}
,type 支持 - type 与 interface 都支持定义对象
什么时候用 type
/interface
因需求而异,你觉得哪个能实现就用哪个。
// 1. 定义对象
// 注意:键值对后面用分号 `;` 而不是逗号 `,`
type Person = {
name: string;
age: number;
}
// 将 Person 当做变量传递进去
const Boss: Person = {
name: 'Jack',
age: 50
}
// 2. 定义函数、参数、以及返回结果
type Foo = (a: number, b: number) => number
const fn: Foo = (num1, num2) => {
return num1 + num2
}
fn(1, 2) // 3
fn(1, 'ff') // Error
// 作为回调函数
function MathOperation(count: Foo ) {
return count(100, 200) // 正确
// return count('100', 200) // Error
}
function count(a, b) {
return a + b
}
// 3. 定义基本类型
type code = boolean
const status:code = true
6. 定义 generic 泛型
泛型
是 TS 中一个很重要的概念,它的使用频率很高,许多地方都会用到,
这里我对泛型的总结就是:类型参数先定义、调用再传递
/****** type 使用泛型 *******/
type Family<T> = {
father: T,
children: T[]
}
const createFamily: Family<string> = {
// 接下来这些都必须是 string 类型
father: 'Tony',
children: ['Jack', 'Tom', 'John']
}
/****** interface 使用泛型 *******/
interface People<J> {
name: string,
age: number,
colors: J[]
}
const Jack:People<string> = {
name: 'Jack',
age: 24,
// 数组里必须都是 string
colors: ['Blue', 'Orange', 'BlueSky']
}
const Tony:People<number> = {
name: 'Jack',
age: 24,
// 数组里必须都是 number
colors: [1, 2, 3]
}
/****** 函数使用泛型 *******/
const arr = []
function add<T>(arg: T): T[] {
arr.push(arg)
return arr
}
add<string>('Jack')
add<number>(100)
add<boolean>(true)
// PS 传递时可以不用加上<>,TS 会自动推导
// add('Jack')
// add(100)
// add(true)
/********* 泛型的参数可以多个 *********/
type Foo<T1, T2> = {
colors: T1[];
numbers: T2[];
}
const createSomething:Foo<string, number> = {
colors: ['Blue', 'Yellow'],
numbers: [100, 200, 300]
}
7. 联合类型 |
|
跟大部分语言计算符号里的 ||
含义一样代表或者
的意思
type Colors = string[]
type Color = 'Blue' | Colors
const createColor:Color = 'Blue'
const CreateManyColor: Color = ['Red', 'Yellow', 'Orange']
const CreateErrorColor: Color = 'Red' // Error
8. 交叉类型 &
&
交叉类型其实就是将两个声明类型进行合并的意思,它可以用于 type
或 泛型
type A = {
name: string
}
type B = {
age: number
}
const User: A & B = {
name: 'Jack',
age: 2000
}
有问题欢迎补充,完!