iT邦幫忙

2021 iThome 鐵人賽

DAY 6
0
自我挑戰組

TypeScript 三十天學習日記系列 第 6

Day 6 基本型別 - part 3

好的,接下來就來介紹剩下的型別~分別是 Union、Aliases、Literal。

Union 型別可以接受指定多種型別給參數,這邊延續 Day 4 的例子:

function add(input1: number, input2: number) {
  const result = input1 + input2
  return result
}

這邊原本指定帶進去 function 的參數只能是 number,但是如果今天想要透過這個 function 相加不只是數字的值的話,那就可以用到 Union 型別,在型別後面加上 |,再接續另一個想指定的型別:

function combine(input1: number | string, input2: number | string) {
  const result = input1 + input2
  return result
}

只要有需要的話,可以指定各種型別到參數,也不限定只能用兩個,要三個也行~

上面的 input1input2 指定了相同的 Union 型別,所以在這邊我們可以用 Aliases 型別把重複指定的型別整合起來:

type Combinable = number | string

接下來就可以把上面重複指定的型別用 Combinable 替換掉了:

function combine(input1: Combinable, input2: Combinable) {
  const result = input1 + input2
  return result
}

Literal 型別則是直接指定該變數的值,根據文件說明:

let x: "hello" = "hello";
// OK
x = "hello";
// ...
x = "howdy";
// error: Type '"howdy"' is not assignable to type '"hello"'.

當指定變數 x 的型別是 "hello" 時,那該變數便不能再改變其值,其實跟 JavaScript 的 const 一樣,但在這邊其實沒有多大的用處,不過如果把這個跟 Union 型別結合在一起的話,在一些情況下會比較實用,比如說有一個 function 的設計只能接收某些指定的值時:

function printText(s: string, alignment: "left" | "right" | "center") {
  // ...
}
printText("Hello, world", "left");
printText("G'day, mate", "centre");
// error: Argument of type '"centre"' is not assignable to parameter of type '"left" | "right" | "center"'.

不只字串的 Literal 型別,數字以及布林值也一樣能夠用這個方式。

今天的學習筆記暫且到此,感謝閱讀。:)


上一篇
Day 5 基本型別 - part 2
下一篇
Day 7 Functions
系列文
TypeScript 三十天學習日記24
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言