引用类型分类

TypeScript 中,把引用类型分为以下两个大类。

  • 复合引用类型:包括数组、元组、函数、对象、类的实例等。

  • 内置引用类型:包括 Date(日期)对象、RegExp(正则表达式)对象、Math(数学)对象等。

复合引用类型通常都需要用户自行定义该类型的组成形式。例如,对于数组和元组,需要自行定义其组成类型和长度;对于函数,需要自行定义其参数、行为及返回值;对于对象或类的实例,则需要自行定义它们的成员、结构和行为。示例代码如下。

//声明数组
let animals: string[] = ["cat", "dog", "bird"];

//声明元组(固定长度数组)
let sex: [string, string] = ["male", "female"];

//声明函数
function printArrayContent(arr: string[]): void {
    console.log(`共有${arr.length}个元素,分别为${arr}`);
}
//以下语句输出"共有3个元素,分别为cat,dog,bird"
printArrayContent(animals);
//以下语句输出"共有两个元素,分别为male,female"
printArrayContent(sex);

//声明对象
let person: { name: string, age: number, selfIntroduction: () => void } =
{
    name: "Hello World",
    age: 111,
    selfIntroduction: function () {
        console.log(`My name is ${this.name}, I'm ${this.age} years old.`);
    }
};
//以下语句输出"My name is Hello World, I'm 111 years old."
person.selfIntroduction();

//声明类
class Phone {
    system: string;
    ram: number;
    rom: number;
    constructor(theSystem: string, theRam: number, theRom: number) {
        this.system = theSystem;
        this.ram = theRam;
        this.rom = theRom;
    }
    bootPrompt(distanceInMeters: number = 0) {
        console.log(`System: ${this.system}, RAM: ${this.ram}GB, ROM: ${this.rom}GB`);
    }
}
let androidPhone: Phone = new Phone("Android", 8, 256);
//以下语句输出System: Android, RAM: 8GB, ROM: 256GB
androidPhone.bootPrompt();

对于内置引用类型,通常已经由编程语言定义好该类型的结构、成员和行为,用户直接使用即可。示例代码如下。

let currentDate = new Date(2022, 5, 1);
//注意,TypeScript中的月份是从0开始的,0代表1月
//以下语句输出"当前时间为Wed Jun 01 2022 00:00:00 GMT+0800 (中国标准时间)"
console.log(`当前时间为${currentDate}`);

let patt1 = new RegExp("e");
//检测是否匹配正则表达式,以下输出"true"
console.log(patt1.test("free"));

后面将详细介绍各种引用类型。