TypeScript 对象语法知识点及案例代码
TypeScript 是 JavaScript 的超集,提供了静态类型检查和其他增强功能。在 TypeScript 中,对象是面向对象编程(OOP)的基础。
一、对象概述
在 TypeScript 中,对象是属性的集合,每个属性都有名称和值。对象可以包含原始值、函数、数组,甚至其他对象。TypeScript 通过接口(Interfaces)和类型别名(Type Aliases)来定义对象的结构,从而实现类型检查。
1.1 对象的创建
对象可以通过 对象字面量、构造函数 或 类 来创建。
二、语法知识点
2.1 对象字面量
使用花括号 {}
来定义对象,并使用 key: value
的形式来添加属性。
// 定义一个对象字面量
let person: { name: string; age: number } = {name: "Alice",age: 30,
};
2.2 接口(Interfaces)
接口用于定义对象的结构,确保对象符合特定的类型。
// 定义一个接口
interface Person {name: string;age: number;greet: () => void;
}// 使用接口创建对象
let person: Person = {name: "Bob",age: 25,greet: function () {console.log(`Hello, my name is ${this.name}`);},
};
2.3 可选属性
接口中的属性可以设置为可选的,使用 ?
符号。
interface Person {name: string;age?: number; // 可选属性
}let person: Person = {name: "Charlie",// age 属性是可选的,可以省略
};
2.4 只读属性
使用 readonly
关键字定义只读属性,属性值只能在对象创建时赋值。
interface Person {readonly id: number;name: string;
}let person: Person = {id: 1,name: "Diana",
};// 尝试修改只读属性会报错
// person.id = 2; // Error
2.5 索引签名
允许对象有动态属性名,使用索引签名定义。
interface StringMap {[key: string]: string;
}let map: StringMap = {firstName: "Eve",lastName: "Adams",
};
2.6 继承接口
接口可以继承其他接口,扩展其属性。
interface Animal {name: string;
}interface Dog extends Animal {breed: string;
}let dog: Dog = {name: "Buddy",breed: "Golden Retriever",
};
2.7 类型别名(Type Aliases)
使用 type
关键字定义类型别名,可以用于对象类型。
type Person = {name: string;age: number;
};let person: Person = {name: "Frank",age: 40,
};
2.8 联合类型与交叉类型
- 联合类型(Union Types):表示一个值可以是几种类型之一,使用
|
符号。 - 交叉类型(Intersection Types):表示一个值同时具有几种类型的属性,使用
&
符号。
type Bird = {wings: number;
};type Fish = {fins: number;
};// 联合类型
let pet: Bird | Fish = {wings: 2,// 或者 fins: 4,
};// 交叉类型
let creature: Bird & Fish = {wings: 2,fins: 4,
};
2.9 泛型对象
使用泛型定义通用的对象类型。
interface Box<T> {value: T;
}let numberBox: Box<number> = {value: 10,
};let stringBox: Box<string> = {value: "Hello",
};
三、案例代码
以下是一些具体的案例代码,展示了如何在 TypeScript 中创建和使用对象。
案例 1:基本对象创建与访问
// 定义一个接口
interface User {id: number;username: string;email: string;isActive: boolean;
}// 创建用户对象
let user: User = {id: 1,username: "john_doe",email: "john@example.com",isActive: true,
};// 访问对象的属性
console.log(`User ID: ${user.id}`);
console.log(`Username: ${user.username}`);
console.log(`Email: ${user.email}`);
console.log(`Is Active: ${user.isActive}`);
输出:
User ID: 1
Username: john_doe
Email: john@example.com
Is Active: true
案例 2:可选属性与只读属性
// 定义一个接口,包含可选属性和只读属性
interface Product {id: number;name: string;price?: number; // 可选属性readonly createdAt: Date;
}// 创建产品对象
let product: Product = {id: 101,name: "Laptop",createdAt: new Date(),
};// 访问可选属性
if (product.price) {console.log(`Price: $${product.price}`);
} else {console.log("Price not available.");
}// 尝试修改只读属性会报错
// product.createdAt = new Date(); // Error// 修改其他属性
product.price = 999.99;
console.log(`Updated Price: $${product.price}`);
输出:
Price not available.
Updated Price: $999.99
案例 3:索引签名
// 定义一个接口,使用索引签名
interface Dictionary {[key: string]: string;
}// 创建字典对象
let dictionary: Dictionary = {apple: "苹果",banana: "香蕉",orange: "橙子",
};// 访问字典中的值
console.log(`Apple in Chinese: ${dictionary.apple}`);
console.log(`Banana in Chinese: ${dictionary.banana}`);
console.log(`Orange in Chinese: ${dictionary.orange}`);
输出:
Apple in Chinese: 苹果
Banana in Chinese: 香蕉
Orange in Chinese: 橙子
案例 4:继承接口
// 定义基类接口
interface Animal {name: string;age: number;
}// 定义派生接口,继承自 Animal
interface Dog extends Animal {breed: string;bark: () => void;
}// 创建 Dog 对象
let dog: Dog = {name: "Rex",age: 5,breed: "German Shepherd",bark: function () {console.log("Woof! Woof!");},
};// 调用方法
dog.bark();
输出:
Woof! Woof!
案例 5:泛型对象
// 定义一个泛型接口
interface Pair<T, U> {first: T;second: U;
}// 创建不同类型的 Pair 对象
let numberPair: Pair<number, number> = {first: 1,second: 2,
};let stringPair: Pair<string, string> = {first: "Hello",second: "World",
};let mixedPair: Pair<string, number> = {first: "Age",second: 30,
};// 访问属性
console.log(`Number Pair: ${numberPair.first}, ${numberPair.second}`);
console.log(`String Pair: ${stringPair.first}, ${stringPair.second}`);
console.log(`Mixed Pair: ${mixedPair.first}, ${mixedPair.second}`);
输出:
Number Pair: 1, 2
String Pair: Hello, World
Mixed Pair: Age, 30
案例 6:联合类型与交叉类型
// 定义两个接口
interface Bird {wings: number;fly: () => void;
}interface Fish {fins: number;swim: () => void;
}// 使用联合类型
let pet: Bird | Fish = {wings: 2,fly: function () {console.log("Flying...");},
};// 调用方法
if ("fly" in pet) {pet.fly();
}// 使用交叉类型
let creature: Bird & Fish = {wings: 2,fins: 4,fly: function () {console.log("Flying...");},swim: function () {console.log("Swimming...");},
};// 调用方法
creature.fly();
creature.swim();
输出:
Flying...
Flying...
Swimming...
四、总结
TypeScript 提供了丰富的语法和功能来定义和管理对象。通过使用接口、类型别名、泛型等特性,开发者可以创建结构化、可维护和可重用的代码。理解这些语法知识点对于有效地使用 TypeScript 进行开发至关重要。