TypeScript 學習系列 | Array, Tuple 和 interface 使用

Array

可以將陣列的元素強制定義為某一個特定的類型,只要在類型的後面加上陣列的括號 [] 即可。

1
2
3
4
// 陣列裡面全部要是數字
let arrOFNumber: number[] = [1, 2, 3, 4]
arrOFNumber.push(5)
arrOFNumber.push('str') //會報錯

Tuple

Tuple的中文可以翻成「元組」,學過 Python 的人對這個資料結構應該比較熟悉。

應用狀況:陣列裡包含除了某特定元素外的類型

1
2
let users: [string, number] = ['emma', 20]
user = ['Andy', 2, true] // true為布林值,會報錯

Object

TypeScript 的 Interface:

  1. 針對使用對象的型態(shape)進行約束,例如屬性或是方法。
  2. 對類(class)進行抽象。
  3. Duck typing:動態類型語言會推測資料的型別,比起關注資料類型,更加在意資料如何被使用。
1
2
3
4
5
6
7
// 建議 class 的字首大寫表示為 interface
// 注意使用分號「;」結尾

interface Person {
name: string;
age: number;
}
1
2
3
4
5
6
// 不能減少或是增加屬性,否則會報錯
let emma: Person = {
name: 'emma',
age: 20,
gender: 'female' //報錯
}

可選屬性

如果 interface 只能依照上面方法使用會沒有彈性。因此可選屬性能夠幫忙解決這個問題,有或沒有都不影響。

使用方法:在變數名稱後面加上問號

1
2
3
4
5
interface Person {
name: string;
age?: number;
}

唯讀屬性

複製 class 的時候才使用,只能用在屬性上,且不能被更改賦予的值。

使用方法:在變數名稱前加上 readonly

1
2
3
4
5
interface Person {
readonly id: number;
name: string;
age?: number;
}

強制更改值的話會報錯

example

作者

Emma Shih

發表於

2020-04-19

更新於

2021-06-23

許可協議

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

評論

You forgot to set the shortname for Disqus. Please set it in _config.yml.