Typescript學習教程,從入門到精通,TypeScript 對象語法知識點及案例代碼(7)

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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/83717.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/83717.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/83717.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

應用BERT-GCN跨模態情緒分析:貿易緩和與金價波動的AI歸因

本文運用AI量化分析框架&#xff0c;結合市場情緒因子、宏觀經濟指標及技術面信號&#xff0c;對黃金與美元指數的聯動關系進行解析&#xff0c;揭示本輪貴金屬回調的深層驅動因素。 周三&#xff0c;現貨黃金價格單日跌幅達2.1%&#xff0c;盤中觸及3167.94美元/盎司關鍵價位&…

命令行登錄 MySQL 報 Segmentation fault 故障解決

問題描述&#xff1a;對 mysql8.0.35 源碼進行 make&#xff0c;由于一開始因為yum源問題少安裝依賴庫 庫&#xff0c;在鏈接時遇到錯誤 undefined reference to&#xff0c;后來安裝了相關依賴庫&#xff0c;再次 make 成功。于是將 mysqld 啟動&#xff0c;再用 mysql -u roo…

Axure設計數字鄉村可視化大屏:構建鄉村數據全景圖

今天&#xff0c;讓我們一同深入了解由Axure設計的數字鄉村可視化大屏&#xff0c;看看它如何通過精心的布局和多樣化的圖表類型&#xff0c;將鄉村的各類數據以直觀、易懂的方式呈現出來&#xff0c;為鄉村管理者提供有力的數據支持。 原型效果預覽鏈接&#xff1a;Axure數字鄉…

3D個人簡歷網站 4.小島

1.模型素材 在Sketchfab上下載狐貍島模型&#xff0c;然后轉換為素材資源asset&#xff0c;嫌麻煩直接在網盤鏈接下載素材&#xff0c; Fox’s islandshttps://sketchfab.com/3d-models/foxs-islands-163b68e09fcc47618450150be7785907https://gltf.pmnd.rs/ 素材夸克網盤&a…

智能開發工具PhpStorm v2025.1——增強AI輔助編碼功能

PhpStorm是一個輕量級且便捷的PHP IDE&#xff0c;其旨在提高用戶效率&#xff0c;可深刻理解用戶的編碼&#xff0c;提供智能代碼補全&#xff0c;快速導航以及即時錯誤檢查。可隨時幫助用戶對其編碼進行調整&#xff0c;運行單元測試或者提供可視化debug功能。 立即獲取PhpS…

Spark 的運行模式(--master) 和 部署方式(--deploy-mode)

Spark 的 運行模式&#xff08;--master&#xff09; 和 部署方式&#xff08;--deploy-mode&#xff09;&#xff0c;兩者的核心區別在于 資源調度范圍 和 Driver 進程的位置。 一、核心概念對比 維度--master&#xff08;運行模式&#xff09;--deploy-mode&#xff08;部署…

sqli—labs第八關——布爾盲注

一&#xff1a;確定注入類型 按照我們之前的步驟來 輸入 ?id1 and 11-- ?id1 and 12-- 界面正常 第二行界面異常空白 所以注入類型為單引號閉合型 二&#xff1a; 布爾盲注 1.判斷是否使用條件 &#xff08;1&#xff09;&#xff1a;存在注入但不會直接顯示查詢結果 …

ARP 原理總結

&#x1f310; 一、ARP 原理總結 ARP&#xff08;Address Resolution Protocol&#xff09;是用于通過 IP 地址解析 MAC 地址的協議&#xff0c;工作在 鏈路層 與 網絡層之間&#xff08;OSI 模型的第三層與第二層之間&#xff09;。 &#x1f501; ARP通信過程&#xff1a; …

SpringCloud——EureKa

目錄 1.前言 1.微服務拆分及遠程調用 3.EureKa注冊中心 遠程調用的問題 eureka原理 搭建EureKaServer 服務注冊 服務發現 1.前言 分布式架構&#xff1a;根據業務功能對系統進行拆分&#xff0c;每個業務模塊作為獨立項目開發&#xff0c;稱為服務。 優點&#xff1a; 降…

機頂盒刷機筆記

疑難雜癥解決 hitool線刷網口不通tftp超時--》關閉防火墻cm201-2卡刷所有包提示失敗abort install--》找個卡刷包只刷fastboot分區再卡刷就能通過了&#xff08;cm201救磚包 (M8273版子&#xff09;&#xff09; 刷機工具 海兔燒錄工具HiTool-STB-5.3.12工具&#xff0c;需要…

Linux動靜態庫制作與原理

什么是庫 庫是寫好的現有的&#xff0c;成熟的&#xff0c;可以復用的代碼。現實中每個程序都要依賴很多基礎的底層庫&#xff0c;不可能每個人的代碼都從零開始&#xff0c;因此庫的存在意義非同尋常。 本質上來說庫是一種可執行代碼的二進制形式&#xff0c;可以被操作系統…

如何通過小智AI制作會說話的機器人玩具?

一、硬件準備與組裝 1. 核心硬件選擇 主控芯片&#xff1a;選擇支持無線網絡連接、音頻處理和可編程接口的嵌入式開發板 音頻模塊&#xff1a;配備拾音麥克風與小型揚聲器&#xff0c;確保語音輸入/輸出功能 顯示模塊&#xff1a;選擇適配的交互顯示屏用于可視化反饋 擴展模…

如何控制郵件發送頻率避免打擾用戶

一、用戶行為 監測用戶與郵件的互動數據&#xff0c;如打開率、點擊率下滑或退訂申請增多&#xff0c;可能是發送頻率過高的警示信號。利用郵件營銷平臺的分析工具&#xff0c;識別這些指標的變動趨勢&#xff0c;為調整提供依據。 二、行業特性與受眾差異 不同行業用戶對郵…

定積分的“偶倍奇零”性質及其使用條件

定積分的“偶倍奇零”性質是針對對稱區間上的奇偶函數積分的重要簡化方法。以下是其核心內容和應用要點&#xff1a; ?一、基本性質 ?偶函數&#xff08;偶倍&#xff09;? 若 f(x) 在 [?a,a] 上為偶函數&#xff08;即 f(?x)f(x)&#xff09;&#xff0c;則&#xff1a; …

如何在 Windows 11 或 10 上安裝 Fliqlo 時鐘屏保

了解如何在 Windows 11 或 10 上安裝 Fliqlo,為您的 PC 或筆記本電腦屏幕添加一個翻轉時鐘屏保以顯示時間。 Fliqlo 是一款適用于 Windows 和 macOS 平臺的免費時鐘屏保。它也適用于移動設備,但僅限于 iPhone 和 iPad。Fliqlo 的主要功能是在用戶不活動時在 PC 或筆記本電腦…

【C/C++】C++并發編程:std::async與std::thread深度對比

文章目錄 C并發編程&#xff1a;std::async與std::thread深度對比1 核心設計目的以及區別2 詳細對比分析3 代碼對比示例4 適用場景建議5 總結 C并發編程&#xff1a;std::async與std::thread深度對比 在 C 中&#xff0c;std::async 和 std::thread 都是用于并發編程的工具&am…

Axure疑難雜癥:垂直菜單展開與收回(4大核心問題與專家級解決方案)

親愛的小伙伴,在您瀏覽之前,煩請關注一下,在此深表感謝!如有幫助請訂閱專欄! Axure產品經理精品視頻課已登錄CSDN可點擊學習https://edu.csdn.net/course/detail/40420 課程主題:垂直菜單展開與收回 主要內容:超長菜單實現、展開與收回bug解釋、Axure9版本限制等問題解…

ASIC和FPGA,到底應該選擇哪個?

ASIC和FPGA各有優缺點。 ASIC針對特定需求&#xff0c;具有高性能、低功耗和低成本&#xff08;在大規模量產時&#xff09;&#xff1b;但設計周期長、成本高、風險大。FPGA則適合快速原型驗證和中小批量應用&#xff0c;開發周期短&#xff0c;靈活性高&#xff0c;適合初創企…

DAY 30 模塊和庫的導入

知識點回顧&#xff1a; 1.導入官方庫的三種手段 2.導入自定義庫/模塊的方式 3.導入庫/模塊的核心邏輯&#xff1a;找到根目錄&#xff08;python解釋器的目錄和終端的目錄不一致&#xff09; 作業&#xff1a;自己新建幾個不同路徑文件嘗試下如何導入 import math # 導入…

MyBatis:動態SQL

文章目錄 動態SQLif標簽trim標簽where標簽set標簽foreach標簽include標簽和sql標簽 Mybatis動態SQL的官方文檔&#xff1a; https://mybatis.net.cn/dynamic-sql.html 動態SQL 動態SQL是 MyBatis的強大特性之一,如果是使用JDBC根據不同條件拼接sql很麻煩&#xff0c;例如拼接…