TypeScript学习笔记3-ts

157 阅读3分钟

TypeScript 基础

ts 是 js 的超集,是 js 、 es6+ 和 类型系统 的合集

安装

安装:npm install typescript --dev, 会在 node_modules 中的 .bin 目录下添加一个 tsc 的命令,这个就是用来编译 ts 代码的,使用 npx tsc 文件名 就可以编译 。

配置文件

使用 npx tsc --init 就可以自动生成 ts 的配置文件 tsconfig.json
tsconfig.json 中的 compilerOption 就包含了很多编译选项,有以下几个常用的选项:

"compilerOption": {
   /** 
     1. 很多项目会将 target 配置为 esnext,这是一个动态版本,指向最新版的下一版
     2. 标准库声明 (内置对象所对应的声明文件),当在代码中使用内置对象,就必须引用对应的标准库,否则ts就找不到对应的类型而报错。
     3. 当 target 选择 es5 的时候,使用的声明文件是 lib.es5.d.ts(es5标准库对应声明文件)
     4. 在设置 target 为 es5 的时候,会发现在代码中使用 symbol 类型会报错,这是因为在lib.es5.d.ts中没有 symbol 的声明,可以将target 改到 es2015,或者使用 lib 选项。
   **/
   "target": "es5" , // 设置编译后的 js 使用的 es 标准
   "lib": ["ES2015","DOM"], // 添加的声明文件
   "module" : "commonjs", // 输出的代码会使用什么方式进行模块化
   "sourceMap" : "true", // 开启源代码映射,在调试时就能使用sourceMap文件调试ts源代码
   "outDir" : "dist", // 编译结果输出的文件夹
   "rootDir" : "src", // 配置原ts代码所在的文件夹
   "strict" : "true", // 开启严格模式,开启所有的严格检查选项,对类型检查会很严格
   /** 
     关闭null校验,对于 string | number | boolean | void 的值可以设置为 null
     "strict" : "false"也会关闭null校验
   **/
   "strictNullChecks" : "false", 
   ...
}

此时在项目目录下直接使用 npx tsc 就可以对src下的目录进行符合配置文件的编译了,如果希望错误信息用中文显现,可以使用 npx tsc --local zh-CN 进行编译。还可以在 vscode 的设置中设置 typescript local 为 zh-CN。

TypeScript 类型

原始类型

string | number | boolean | void ( undefined ) | undefined | null | symbol

Object类型

// object 类型是指除了原始类型以外的其它类型,除了普通对象以外还包含数组、函数。。。
const foo1:object = {name:'lily', age:28}
// 限制普通对象可以用 对象字面量 的形式,或者是「接口」
const foo2:{name: string, age: number} = {name:'lily', age:28}

数组类型

// 数组类型有两种表现方式
const arr1: Array<number> = [1,2,3]
const arr2: number[] = [1,2,3]

元组类型

// 元组就是明确元素数量和每个元素类型的数组
const tuple: [number, string] = [18, 'lily']

枚举类型:数字枚举 | 字符串枚举

// 比如有三个状态值,分别存储为0,1,2,为了表示的更清楚可以使用数字枚举进行描述
enum status1 {
  pending = 0,
  fullfilled = 1,
  rejected =2
}
// 使用枚举值
const code = status1.fullfilled // 1
// 写的时候也可以省略等号后面的值, 默认第一个值为 0 ,此后的项都是在第一项上递增
enum status2 {
  pending = 5,
  fullfilled, //6
  rejected    //7
}
// 字符串枚举
enum status2 {
  pending = 'PENDING',
  fullfilled = 'FULLFILLED',
  rejected = 'REJECTED'
}

枚举类型会入侵到运行时的代码,会影响编译后的代码。枚举类型在编译后会生成一个双向键值对对象。status1 编译之后:

var status1;
(function(status1){
   status1[status1["pending"] = 0] = "pending";
   status1[status1["fullfilled"] = 1] = "fullfilled";
   status1[status1["rejected"] = 2] = "rejected";
})(status1 || (status1 = {}));
var code = status1.fullfilled

这是为了防止在代码中用到 status1[0] 来获取值 'pending' 的情况,如果确定不会这么使用,那么使用常量来定义枚举更好

// 添加 const 声明
const enum status1 {
  pending = 0,
  fullfilled = 1,
  rejected =2
}
const code = status1.fullfilled // 1

======> 编译后

// 枚举类型会被移除,枚举值会替换回具体值,名称会以注释的形式表现
var code = 0 /** pending **/

函数类型

// 函数声明
function func1 (a: number, b: number): string {
  return 'func1'
}
// 函数表达式
const func2: (a: number, b: number) => string = function (a: number, b: number): string {
  return 'func2'
}

任意类型

any: ts 不会对 any 类型的值做检查

学习自拉钩教育前端视频