ts基础—基础类型

522 阅读2分钟

一、基础类型

1.1 布尔值

// 其他类型都报错
let bool: boolean = true
let bool2: boolean = false

1.2 数字类型

let num: number = 20

 // 十六进制
let num2: number = 0x14

 // 二进制
let num3: number = 0b10100

 // 八进制
let num4: number = 0o24

1.3 字符串

let person: string = 'jack'

// 模板字符串
let age: number = 18
let result: string = `my name is ${person}, I will be ${age + 1} year old next month`

// es5拼接
let result2: string = 'my name is ' + person + ', I\'ll be ' + (age + 1) + ' year old next month'

1.4 数组

// 数组每一项都要是number
let list: number[] = [1, 2, 3]

// 和上面写法效果一模一样
let list2: Array<number> = [1, 2, 3]

1.5 元组

let x: [string, number] = ['1', 2] // 第一位是字符串, 第二位是数字

x = [1, '2'] // 飘红
x[0].substr(0, 1) // 可以使用substr方法
x[1].substr(0, 1) // 飘红 因为数字类型没有substr方法
x[3] = 'world' // 越界元素飘红

1.6 枚举类型

enum Color {
  Red,
  Green,
  Blue
}

let c:Color = Color.Blue

console.log(c) // 2

也可以指定从特定数字开始排序

enum Color {
  Red = 1,
  Green,
  Blue
}

let c:Color = Color.Blue

console.log(c) // 3
enum Color {
  Red = 1,
  Green = 2,
  Blue = 4
}

let c:Color = Color.Blue

console.log(c) // 4

也可以反查

enum Color {
  Red = 1,
  Green,
  Blue = 4
}

let colorName:string = Color[4]

console.log(colorName)

编译结果

var Color;
(function (Color) {
    Color[Color["Red"] = 1] = "Red";
    Color[Color["Green"] = 2] = "Green";
    Color[Color["Blue"] = 4] = "Blue";
})(Color || (Color = {}));
var colorName = Color[4];

1.7 any

有时候我们不希望进行类型检查,就可以用any

let something: any = 'something'
// 可以改成数字类型
something = 123
// 可以改成布尔类型
something = true
// 数组中可以加任意类型的值
let list: any[] = [1, true, 'some']

1.8 void

常在函数没有任何返回值时使用

function warnUser(): void {
 console.log('this is warning')
}
let x: void = undefined // 只能复制undefined或null

1.9 never

函数没有返回值或者抛错的时候常用never

可以赋值给任何类型

// 抛出异常
function error(message: string): never {
  throw new Error(message)
}
// 永不结束的函数
function inifiniteLoop(): never {
  while (true) {

  }
}

1.10 Object

declare function create(o: object | null): void;

create({prop: 0}) 
create(null)

create(1) // 飘红
create('1') // 飘红

1.11 类型断言

let someValue:any = 'string'
 // 当我们明确知道变量是什么类型的时候,可以把变量转换为该类型
let strLength:number = (<string>someValue).length
let strLenght2:number = (someValue as string).length // 不同语法