模式切换
对象
在 TypeScript 中,对象是一种复合数据类型,它允许你存储多个值作为一个单一的实体。对象由键(key)和值(value)对组成,其中键是字符串类型,而值可以是任何数据类型,包括原始数据类型、对象、数组等。
TypeScript 的对象类型是基于 JavaScript 的对象类型扩展而来的,因此它支持所有的 JavaScript 对象特性,并添加了类型安全性和其他强大的功能。
对象的字面量表示法
你可以使用对象字面量表示法来创建一个对象,并为其指定属性和方法。
typescript
let person: { firstName: string; lastName: string; };
person = {
firstName: "John",
lastName: "Doe"
};
console.log(person.firstName); // 输出 "John"
访问对象属性
你可以通过点运算符(.)来访问对象的属性。
typescript
let person = {
firstName: "John",
lastName: "Doe",
fullName(): string {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(person.firstName); // 输出 "John"
console.log(person.lastName); // 输出 "Doe"
console.log(person.fullName()); // 输出 "John Doe"
对象的类型注解
你可以为对象提供类型注解,以确保它符合特定的结构。
typescript
interface Person {
firstName: string;
lastName: string;
age?: number; // 可选属性
}
let john: Person = {
firstName: "John",
lastName: "Doe"
};
// 还可以这样定义带有可选属性的对象
let jane: Person = {
firstName: "Jane",
lastName: "Smith",
age: 30
};
对象的初始化
你也可以在声明对象的同时初始化它。
typescript
let person = {
firstName: "John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName()); // 输出 "John Doe"
对象的解构赋值
TypeScript 支持对象的解构赋值,允许你从对象中提取属性值。
typescript
let person = {
firstName: "John",
lastName: "Doe"
};
let {firstName, lastName} = person;
console.log(firstName); // 输出 "John"
console.log(lastName); // 输出 "Doe"
对象的可索引性
你可以定义具有可索引签名的对象类型,这允许你像访问数组一样访问对象的属性。
typescript
interface StringArray {
[index: number]: string;
}
let myArray: StringArray;
myArray = ["Bob", "Fred"];
console.log(myArray[0]); // 输出 "Bob"
对象的扩展
你可以使用扩展运算符(...)来复制对象的属性。
typescript
let person1 = {
firstName: "John",
lastName: "Doe"
};
let person2 = {...person1, age: 30};
console.log(person2.firstName); // 输出 "John"
console.log(person2.lastName); // 输出 "Doe"
console.log(person2.age); // 输出 30