Skip to content

基本数据类型

TypeScript 支持与 JavaScript 几乎相同的数据类型,此外还提供了枚举类型

  • 布尔值
  • 数字
  • 字符串
  • 数组(数组内元素类型相同)
  • 元组(元组内元素类型可以不相同)
    • 访问一个已知元素会得到正确的类型
    • 访问越界元素会报错(高版本)
  • 枚举(默认情况下元素编号从 0 开始,可以手动指定编号)
  • null
  • undefined
// 布尔值 boolean
const isDone: boolean = false

// 数字 number
const decLiteral: number = 1
const hexLiteral: number = 0xf00d
const binaryLiteral: number = 0b10
const octalLiteral: number = 0o3

// 字符串 string
const str: string = '123'

// 空值 void
function alert(): void {
  alert('test!')
}

// null 和 undefined
// 指定"strictNullChecks": false时,null和undefined是所有类型的子类型
// 指定"strictNullChecks": true时b, c, d, g, h会报错
const a: void = undefined
const b: void = null
const c: number = null
const d: number = undefined
const e: null = null
const f: undefined = undefined
const g: null = undefined
const h: undefined = null

// Symbol
const sym: symbol = Symbol('key')

// BigInt
// 需要使用BigInt将数字转换为BigInt
const big: bigint = BigInt(2**55)

// any
let notSure: any = 2
notSure = '2'

// unknown
// unknown 是any类型对应的安全类型,在使用前必须对类型做出判断
let value: unknown
value = 123
if (typeof value === "number") {
  value += 1
}
value = [1,2,3]
if (value instanceof Array) {
  value.push(4)
}

// never
function error(msg: string): never {
  throw new Error(msg)
}
// 空数组,而且永远为空,不能添加元素
const empty: never[] = []

// 数组
const arr: number[] = [1, 2]
const arr1: Array<number> = [1, 2]
interface NumberArray {
  [index: number]: number
}
const arr2: NumberArray = [1, 2]
// 注:类数组不是数组类型,比如arguments等,事实上常见的类数组都有自己的接口定义,如 IArguments, NodeList, HTMLCollection 等

// 元组
const list: [string, number] = ['123', 123]

// 枚举
// 数字枚举
enum Color {Red = 1, Green, Blue}
const color: Color = Color.Green    // 2
const colorName: string = Color[2]  // Green
// 字符串枚举
enum Direction {
  Up = 'Up',
  Down = 'Down',
  Left = 'Left',
  Right = 'Right',
}
// 异构枚举
enum BooleanLike {
  No = 0,
  Yes = 'Yes'
}
// 常量枚举
const enum ValueEnums {
  a = 'A',
  b = 'B'
}
const enumValue = ValueEnums.a

// Object
// object 表示非原始类型,也就是除 number,string,boolean,symbol,null 或 undefined 之外的类型。
// 我们看到,普通对象、枚举、数组、元组通通都是 object 类型。
let obj: object
obj = {}
obj = []
obj = Color

注:TypeScript 的原始类型写为 boolean、number、string 等等,在 JavaScript 中都有类似的关键字 Boolean、Number、String。 后者是 JavaScript 中的构造函数,而 Typescript 中 number 仅仅便是类型。