【TypeScript专栏】二、TypeScript基础(一)

108 阅读2分钟

2.1 JavaScript 基础知识补充

  • 数据类型

    • 7种原始类型

      • Boolean 布尔
      • Null 空
      • Undefined 未定义
      • Number 数字
      • BigInt 任意精度的整数

        它解决了传统 Number 类型因使用 64 位浮点数格式而无法安全表示超大整数(超过 ±(2^53 - 1))的问题。

      • String 字符串
      • Symbol 唯一
    • Object

      除 Object 以外的所有类型都是不可变的(值本身无法被改变)。称这些类型的值为“原始值”。

  • 类数组

    • 是普通对象,具有 length 属性和数字索引访问能力,但不继承 Array.prototype,因此无法直接调用数组方法。

    • 区别

      • 数组:是 JavaScript 的内置对象,用于存储有序的元素集合,继承自 Array.prototype,拥有丰富的数组方法(如 pushmapforEach 等)。
      • image.png
    • 转换为数组的方法

      // Array.from() (推荐)
      const argsArray = Array.from(arguments);
      
      // 扩展运算符 ...
      const nodesArray = [...doucment.querySelectorAll('div')];
      
      // Array.prototype.slice.call() (旧版本兼容)
      const argsArray = Array.prototype.slice.call(arguments);
      

2.2 原始数据类型

// 布尔类型
let isDone: boolean = false;

// 数字类型
let age: number = 12;

// 字符串类型
let firstName: string = 'zhangsan';
let message: string = `Hello,${firstName}`

// null 和 undifined
// 这两种类型是所有类型的子类型
// 也就是说这两种类型值可以赋值给其他类型
let u: undefined = undefined;
let n: null = null;

2.3 Any类型

  • 在无法判断所写数据的类型时,或临时完善ts校验时,可用。
  • 允许赋值给任意类型。
  • 一般情况下,要避免使用any类型,因为这个类型可以任意调用方法和属性,就会更容易出现错误,丧失类型检查的作用。
let notSure: any = 4;
notSure = 'maybe a string';
notSure = true;

notSure.myName;
notSure.getName(); 
// 调用属性和方法均不会报错,因为默认为any 任意类型

2.4 数组

// 声明 数字类型的数组
// 数组的元素,不允许出现 数字以外的类型
let arrOfNumber: number[] = [1,2,3];

// 在指定好类型后,在调用这个数组后
// 可以自动获得数组上所有的方法
// (输入 数组名.  后,存在的方法会自动弹出提示框)
arrOfNumber.push(5);

image.png

2.5 类数组

function test() {
    console.log(arguments);
    // arguments 就是类数组
    // 而类数组有已经内置的类型 IArguments 类型
    // 还有诸多已经存在的内置类型
}

2.6 元组

  • 合并不同类型的对象 将内部的数据类型进行更精细的确定
  • 起源于函数式编程
// 存储的数组元素,顺序和类型必须对应
// 因为仍旧是数组,所以可以使用数组的方法
// 如 push,但只可添加设定好的两种类型的值
let user: [string, number] = ['zhangsan', 20];