TypeScript 中的可選鏈接

TypeScript 中的可選鏈接

在本文中,我們將解釋 TypeScript 中的可選鏈接。

YouTube Video

TypeScript 中的可選鏈接

TypeScript 中的可選鏈接是一個有用的功能,用於訪問深層嵌套對象或數組的屬性。此功能可防止在訪問不存在的屬性時出現錯誤,使您能夠編寫簡潔且可讀性更高的代碼。

什麼是可選鏈接?

可選鏈接操作符(?.)在訪問不存在的對象屬性或方法時返回 undefined。如果屬性不存在,此操作允許代碼繼續運行而不會拋出錯誤。

例如,在訪問嵌套對象的屬性時,如下面示例所示,如果使用普通方法,當屬性不存在時會引發錯誤。

範例

 1interface User {
 2    name?: string;
 3    address?: {
 4        city?: string;
 5        postalCode?: string;
 6    };
 7}
 8
 9const user: User = {
10    name: 'Alice'
11};
12
13// Normal access
14console.log(user.address.postalCode); // Error: Cannot read property 'postalCode' of undefined
  • 在這種情況下,如果address不存在,將會發生錯誤。可選鏈接可用於防止此類情況。

使用可選鏈式調用的範例

 1interface User {
 2    name?: string;
 3    address?: {
 4        city?: string;
 5        postalCode?: string;
 6    };
 7}
 8
 9const user: User = {
10    name: 'Alice'
11};
12
13console.log(user.address?.postalCode); // undefined
  • 使用可選鏈接可以避免錯誤,當屬性不存在時返回 undefined

如何使用可選鏈接

可選鏈接可用於各種場景,例如屬性訪問、函數調用和數組訪問。我們將解釋如何使用每種情況。

訪問屬性

您可以安全地訪問對象的嵌套屬性。

 1interface Company {
 2    name: string;
 3    location?: {
 4        city?: string;
 5        country?: string;
 6    };
 7}
 8
 9const company: Company = {
10    name: 'Tech Corp',
11    location: {
12        city: 'New York'
13    }
14};
15
16console.log(company.location?.city); // 'New York'
17console.log(company.location?.country); // undefined

這段程式碼使用可選鏈(Optional Chaining)來存取 company 物件中的 location 屬性存在時,才能存取其下的 citycountry 屬性。

函數調用

可選鏈接還可以在調用函數之前檢查函數是否存在。

 1interface User {
 2    name?: string;
 3    greet?: () => void;
 4}
 5
 6const user: User = {
 7    name: 'Bob',
 8    // greet is undefined
 9};
10
11// Check if the function exists before calling it
12user.greet?.(); // The call is not made, and no error occurs

這段程式碼使用可選鏈安全地調用 greet 函式,只有當其存在時才會執行。即使該函式未定義,也不會發生錯誤。

數組訪問

可選鏈接可應用於數組,用於檢查元素是否存在。

 1interface Team {
 2    members?: string[];
 3}
 4
 5const team: Team = {
 6    members: ['Alice', 'Bob', 'Charlie']
 7};
 8
 9console.log(team.members?.[0]); // 'Alice'
10console.log(team.members?.[5]); // undefined

這段程式碼僅在 team.members 存在時取用陣列元素,存在的索引會返回值,不存在則返回 undefined

可選鏈與空值合併運算子

可選鏈接返回 undefined,但有時這並不夠用。在這種情況下,可以使用 TypeScript 3.7 引入的 空值合併運算子??),為 nullundefined 提供預設值。

 1interface User {
 2    name?: string;
 3    address?: {
 4        city?: string;
 5        postalCode?: string;
 6    };
 7}
 8
 9const user: User = {
10    name: 'Carol'
11};
12
13// Use 'Unknown' as the default value if name does not exist
14const userName = user.name ?? 'Unknown';
15
16console.log(userName); // 'Carol'

結合可選鏈接符時,您可以撰寫更靈活的代碼。

1console.log(user.address?.postalCode ?? 'Not provided'); // 'Not provided'

使用可選鏈接時的注意事項

在使用可選鏈時,請注意以下幾點:。

  • 不必要的可選鏈使用

    • 對於保證存在的屬性或方法使用可選鏈會讓程式碼變得不必要地冗長。最好僅在訪問目標的存在不確定時使用。
  • 輸入錯誤

    • 過度使用可選鏈可能讓你更難發現因打字錯誤而存取到不正確屬性的問題。請執行適當的類型檢查並謹慎使用。

程式碼摘要

 1interface User {
 2    name?: string;
 3    address?: {
 4        city?: string;
 5        postalCode?: string;
 6    };
 7}
 8
 9const user: User = {
10    name: 'Alice',
11    address: {
12        city: 'Tokyo'
13    }
14};
15
16// Example of optional chaining
17console.log(user.address?.city); // 'Tokyo'
18console.log(user.address?.postalCode); // undefined
19
20// Using optional chaining combined with nullish coalescing
21console.log(user.address?.postalCode ?? 'Not provided'); // 'Not provided'

總結

TypeScript 中的可選鏈接提供了簡潔的代碼,同時避免在訪問深層嵌套對象或陣列時出現錯誤。此外,結合空值合併運算子可以設定預設值,令邏輯更加彈性。當適當使用時,它可以顯著提高代碼的安全性和可讀性。

您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。

YouTube Video