1. 对象的声明:
let person: {
firstName: string;
lastName: string;
age: number;
};
person = {
firstName: "John",
lastName: "Doe",
age: 30
};
2. 对象的属性和方法:
let car: {
brand: string;
model: string;
start: () => void;
};
car = {
brand: "Toyota",
model: "Camry",
start: function() {
console.log("Engine started");
}
};
car.start(); // 输出: Engine started
3. 类型别名和接口:
可以使用类型别名或接口来定义对象的结构:
type Person = {
firstName: string;
lastName: string;
age: number;
};
let person: Person = {
firstName: "John",
lastName: "Doe",
age: 30
};
或者:
interface Car {
brand: string;
model: string;
start: () => void;
}
let car: Car = {
brand: "Toyota",
model: "Camry",
start: function() {
console.log("Engine started");
}
};
car.start(); // 输出: Engine started
4. 动态属性名:
let propertyName: string = "firstName";
let person: { [key: string]: string } = {
[propertyName]: "John",
lastName: "Doe"
};
console.log(person.firstName); // 输出: John
5. 可选属性:
let person: {
firstName: string;
lastName?: string; // 可选属性
age: number;
};
person = {
firstName: "John",
age: 30
};
6. 对象解构:
let person: {
firstName: string;
lastName: string;
age: number;
} = {
firstName: "John",
lastName: "Doe",
age: 30
};
let { firstName, lastName, age } = person;
console.log(firstName, lastName, age); // 输出: John Doe 30
这些是 TypeScript 中关于对象的一些基本用法。对象是一种非常灵活的数据结构,用于组织和存储相关的信息。
转载请注明出处:http://www.pingtaimeng.com/article/detail/13023/TypeScript