typeScript学习笔记

147 阅读3分钟

1. 环境搭建

安裝

npm i -g typescript

命令

  1. 编译:tsc 编译ts文件

    tsc ./src/helloWord.ts

  2. 指定编译目录:

    tsc --outdir 指定目录 编译ts文件

    tsc --outdir ./dist ./src/helloWord.ts

  3. 指定编译后js版本:

    tsc --target es版本 编译ts文件, 默认编译后的js版本是es3

    tsc --target es6 ./src/helloWord.ts

  4. 监听ts文件变更,自动编译

    tsc --watch 编译ts文件

    tsc --watch ./src/helloWord.ts

配置文件

  1. typescript的配置文件默认为tsconfig.json

  2. 通过配置文件编译ts:

    tsc -p 配置文件所在目录,如果配置文件的命名为tsconfig.json,那么命令可以只写到tsconfig.json所在目录,如果命名不是 tsconfig.json,则需要指定配置文件名。

    tsc -p ./configs/tsconfig.ts

  3. 配置项:

{
  "compilerOptions": {
    "outDir": "./dist", //  指定编译后js存放文件夹,目录路径相对于配置文件指定
    "target": "es6", // 编译后目标js文件的版本
    "watch": true, // 是否启动监听模式
    "strictNullChecks": true //	严格的null值检查,不允许将null,undefined赋值给其他类型
  },
  /* 
    include为需要编译的文件的数组
    **代表src下所有后代文件夹
    *代表文件夹下所有文件
    *.ts代表所有.ts后缀文件
  */
  "include": ["./src/**/*.ts"]
}

2. 类型系统

类型系统包含两个重要组成部分:

  • 类型标注(定义,注解) - typing

  • 类型检测 (检查) - type-checking

类型标注

类型标注就是在代码中给数据(变量, 函数(参数,返回值))添加类型说明,当一个变量或者函数(参数,返回值)被标注以后,就不能存储或者传入与标注类型不符合的类型。

在typescript中,类型标注的基本语法格式为:

数据载体:类型
let str: string = 'helloWord';

typescript的类型标注,可以分为:

  • 基础的简单的类型标注
  • 高级的深入的类型标注

1.基础的简单的类型标注

  • 基础类型

    基础类型包含:string,number,boolean

    let title: string = 'helloWord';
    let num: number = 100;
    let flag: boolean = true;
    
  • 空和未定义类型

    因为 null 和 undefined 这两种类型有且只有一个值, 因此在标注一个变量为 null 或 undefined 类型,就表示改变量不可修改

    let a: null = null; //	ok
    a = 1; //	error
    let b: undefined = undefined; //	ok
    b = 'string'; //	error
    

    默认情况下 null 和 undefined 是所有类型的子类型,因此可以把其他类型的变量的值设置为 null 或 undefined

    let a: number = 100;
    a = undefined;
    a = null;
    

    如果一个变量声明了,但是没有赋值,那么这个变量的值默认为 undefined,如果这个变量没有标注类型,那么这个变量的默认类型为any。

  • 对象类型

    • 内置对象类型

      在javascript中,有很多内置对象类型,如:Object, Array, Date 等等,我们可以通过对象的 构造函数 或 类 来进行标注

      let a: object = {};
      let arr: Array<number> = [1, 2, 3];
      let arr2: Array<string> = ['a', 'b', 'c'];
      let date: Date = new Date();
      
    • 自定义对象类型

      实际开发过程中,我们需要自定义对象结构,可以通过以下方式进行标注:

      • 字面量标注
      • 接口
      • 定义 类 或者 构造函数
      /*
         字面量标注
         优点:方便,直接
         缺点:不利于维护 复用
      */
      let user1: {userName: string, age: number} = {
         userName: 'name',
         age: 18
      };
      /*
         接口
         优点:复用性高
         缺点:接口只能作为类型标注使用,不能作为具体值,它只是一种抽象的结构定义,并不是实体,没有具体功能实现
      */
      interface Person {
         userName: string;
         age: number;
      }
      let user2: Person = {
         userName: 'name',
         age: 18
      }
      /*
         类与构造函数
         优点:功能相对强大,定义实体的同时也定义了对应的类型
         缺点:较为复杂
      */
      class Person {
         constructor (public userName: string, public age: number) {}
      }
      let user3: Person = new Person('name', 18)
      
  • 数组类型

类型检测

对数据的类型进行检测,类型检测只能检测类型,不能检测数据的具体值