iT邦幫忙

2021 iThome 鐵人賽

DAY 10
0
自我挑戰組

從新手開始TypeScript系列 第 10

Day10-TypeScript(TS)的索引型別(Indexable Type)

今天來介紹TypeScript(TS)的索引型別(Indexable Type),
今天是輕鬆的一天,
大家快樂學習。

使用介面型別(Interface)來描述索引型別(Indexable Type),
指明索引以及回傳值型別,也稱索引簽名(Index Signature)。

範例如下,
先宣告一個介面型別
用來描述索引型別

interface indexArr {
    [index: number]: string;
}

接著宣告新的變數為此介面型別,
接著透過索引值從0開始第一項,
分別可以找出各索引值所對應的字串,如下。

let arr: indexArr = ['AAA', 'BBB', 'CCC'];
let x: string = arr[0];
let y: string = arr[1];
let z: string = arr[2];

console.log(x); //AAA
console.log(y); //BBB
console.log(z); //CCC

今日結語

索引值在程式碼裡面是非常重要的,
尤其是要找出規則性、分組,或是跑迴圈...等,
是必須想辦法熟悉它的喔。


上一篇
Day9-TypeScript(TS)的介面型別(Interface)Part 2
下一篇
Day11-TypeScript(TS)的類別(Class)
系列文
從新手開始TypeScript30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言