typeScript学习笔记

124 阅读1分钟

1、类型

基本类型

八种数据类型,分别是:number,string,boolean,null,underfun,bigint,symbol,void

其它类型

  • any: 不清楚是什么类型情况下使用
  • unknown 和any差不多,区别是未被赋值之前不可以直接使用
  • never: 永远拿不到返回值的类型,如函数里面有死循环,报错
  • 数组: 两种方式 泛类型Array <number>和 元素类型后面接上 [],number[]
  • 元组: 和数组差不多,只不过[]内部元素类型可以不同
  • Object: 非原始数据类型

枚举类型

它用于声明一组命名的常数,当一个变量有几种可能的取值时,可以将它定义为枚举类型。

数字枚举

// 虽然没给赋值,但是是从0开始默认展开的
enum Direction {
    Up,
    Down,
    Left,
    Right
}

console.log(Direction.Up === 0); // true
console.log(Direction.Down === 1); // true
console.log(Direction.Left === 2); // true
console.log(Direction.Right === 3); // true

// 因此当我们把第一个值赋值后,后面也会根据第一个值进行累加:

enum Direction {
    Up = 10,
    Down,
    Left,
    Right
}

console.log(Direction.Up, Direction.Down, Direction.Left, Direction.Right); 
// 10 11 12 13

字符串枚举

// 没啥说的
enum Direction {
    Up = 'Up',
    Down = 'Down',
    Left = 'Left',
    Right = 'Right'
}

console.log(Direction['Right'], Direction.Up); // Right Up

异构枚举

// 既有字符串又有数字
enum BooleanLikeHeterogeneousEnum {
    No = 0,
    Yes = "YES",
}

反向映射

联合枚举类型

接口

不要把接口和枚举搞混了,接口是描述类型的(比如描述一个对象类型),枚举是固定值,声明对象用的 接口可以集成

interface User {
    name: string
    age?: number
    readonly isMale: boolean
}

有点,增加了新特性,如公有私有,内部访问变量,静态类 疑惑,类如何当接口使用

函数

泛型

一个参数包含多个类型