返回

TypeScript 中的类型(上)

前端

  1. 基本类型

TypeScript 中的基本类型包括数字(number)、字符串(string)、布尔值(boolean)、undefined 和 null。

  • 数字类型(number):可以是整数或小数,可以是十进制、八进制或十六进制。
  • 字符串类型(string):由双引号或单引号括起来的字符序列。
  • 布尔值类型(boolean):只有两个值:true 和 false。
  • undefined 类型:表示变量未赋值。
  • null 类型:表示变量的值是明确的空值。
let num: number = 123;
let str: string = "Hello TypeScript";
let bool: boolean = true;
let undef: undefined = undefined;
let nul: null = null;

2. 引用类型

引用类型是指变量指向内存中的对象,包括对象(object)、数组(array)、函数(function)。

  • 对象类型(object):由花括号括起来的一组键值对。
  • 数组类型(array):由方括号括起来的一组有序值。
  • 函数类型(function):由 function 定义的代码块。
let person: object = { name: "John", age: 30 };
let numbers: array = [1, 2, 3, 4, 5];
let greet: function = function() { console.log("Hello TypeScript"); };

3. 联合类型

联合类型是指变量可以是多种类型之一。联合类型使用管道符号(|)连接不同的类型。

let numOrStr: number | string = "123";
numOrStr = 123;

4. 交叉类型

交叉类型是指变量可以是多种类型的交集。交叉类型使用 & 符号连接不同的类型。

interface Person {
  name: string;
  age: number;
}

interface Employee extends Person {
  salary: number;
}

let employee: Employee = { name: "John", age: 30, salary: 10000 };

5. 元组

元组是具有固定长度和固定类型的有序值列表。元组使用方括号括起来,每个元素之间使用逗号分隔。

let tuple: [string, number, boolean] = ["Hello", 123, true];

6. 枚举

枚举是一种特殊的类型,用于定义一组常量。枚举使用 enum 关键字定义,枚举成员之间使用逗号分隔。

enum Colors {
  Red,
  Green,
  Blue
}

let color: Colors = Colors.Red;

7. 泛型

泛型是指在定义类型时使用类型变量,使类型可以适用于多种不同的数据类型。泛型使用尖括号 < > 定义,类型变量放在尖括号内。

function identity<T>(x: T): T {
  return x;
}

let num: number = identity(123);
let str: string = identity("Hello TypeScript");

8. 类型保护

类型保护是指在运行时检查变量的类型。类型保护可以使用 typeof 运算符、instanceof 运算符、in 运算符来实现。

if (typeof num === "number") {
  // do something
}

if (person instanceof Person) {
  // do something
}

if ("name" in person) {
  // do something
}

9. 类型断言

类型断言是指在编译时告诉编译器变量的类型。类型断言可以使用 < > 运算符或 as 关键字来实现。

let num: any = "123";
let num2: number = <number>num; // or num2 = num as number;

10. 类型转换

类型转换是指将变量从一种类型转换为另一种类型。类型转换可以使用 parseInt()、parseFloat()、Boolean()、String() 等函数来实现。

let num: number = parseInt("123");
let str: string = String(123);
let bool: boolean = Boolean(1);