了解TypeScript中的聯合類型接口

了解TypeScript中的聯合類型接口

TypeScript 接口(interfaces)的聯合類型

TypeScript 是一種 JavaScript 的超集,它提供了類型系統,讓開發者可以在程式碼中指定變數的類型,以提升程式碼的可讀性和可維護性。在 TypeScript 中,接口(interfaces)是一種非常重要的概念,它可以讓開發者定義一種特定的類型,以便在程式碼中使用。

在 TypeScript 中,接口(interfaces)可以使用聯合類型(union types)來定義,聯合類型可以指定一個變數可以接受多種類型的值,例如:

interface Person {
  name: string | null;
  age: number | null;
}

上面的程式碼定義了一個 Person 接口,它的 name 屬性可以接受 string 或 null 的值,age 屬性可以接受 number 或 null 的值。

聯合類型也可以用於函式的參數,例如:

function greet(name: string | null): void {
  if (name) {
    console.log(`Hello, ${name}`);
  } else {
    console.log('Hello, stranger');
  }
}

上面的程式碼定義了一個 greet 函式,它的參數 name 可以接受 string 或 null 的值,如果傳入的是 string,則會顯示出 Hello, [name] 的訊息,如果傳入的是 null,則會顯示出 Hello, stranger 的訊息。

聯合類型也可以用於函式的回傳值,例如:

function getName(): string | null {
  const name = 'John';
  return name;
}

上面的程式碼定義了一個 getName 函式,它的回傳值可以是 string 或 null,如果傳回的是 string,則會傳回一個字串,如果傳回的是 null,則會傳回 null。

總結來說,TypeScript 接口(interfaces)的聯合類型(union types)可以讓開發者定義一種特定的類型,讓變數可以接受多種類型的值,以提升程式碼的可讀性和可維護性。

推薦閱讀文章

推薦閱讀文章

            <a href="https://ithelp.ithome.com.tw/articles/10206890">TypeScript 接口(interfaces)的聯合類型</a><br>
            <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html">TypeScript 進階類型</a><br>
            <a href="https://ithelp.ithome.com.tw/articles/10206890">TypeScript 接口(interfaces)的聯合類型</a><br>
            <a href="https://www.typescriptlang.org/docs/handbook/interfaces.html">TypeScript 接口(interfaces)</a><br>
            <a href="https://ithelp.ithome.com.tw/articles/10206890">TypeScript 接口(interfaces)的聯合類型</a

延伸閱讀本站文章

更多TypeScript相關文章

推薦學習youtube影片

發佈留言