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 進行開發至關重要。