對 TypeScript 還不是很熟悉先從 TypeScript Foundations 12題開始練習
Index Signatures 索引特徵
使用情境
不知道物件型別的屬性名稱,但知道值的型別,就可以用 index signature 來描述 value 的型別。
物件型別,可以接受任何key,並回傳value的型別。
key常用string型別,因為JavaScript搜尋物件屬性,會預設把key的型別轉換為string。
當key使用number或boolean型別,仍然會運作,因為會被強制轉為string。
reference: Property names
Each property name is a string or a Symbol.
Any other value, including a number, is coerced to a string. This outputs 'value', since 1 is coerced into '1'.
const object = {};
object["1"] = "value";
console.log(object[1]);
reference: typehero/index-signatures-description
JavaScript object keys can only be strings or symbols. THAT'S IT. period. No other data types are possible to store as object keys.
JavaScript will coerce anything you store as an object key to a string.
TypeHero Description
像是results物件,userID map 到 follower count,results物件的key是隨機字串,value是number型別。
{
"info": {
"count": 9001,
"currentPage": 1,
"pages": 22
},
"results": {
"user_ddb04d2e-21ff-4c68-9bdc-135c16c8e74a": 0,
"user_1e118b25-c0b9-4bfc-8d04-901ad8a2eb20": 3,
"user_7c56283c-6a5e-4d79-bdd0-9c6a3cafd2c4": 15,
// ... for many more rows in this page
}
}
Index Signatures 的使用
解題是觀察test的程式碼中,來寫以下3個型別名稱的型別
test的程式碼
index signature 大多出現在interface章節內介紹
TypeScript - Object Types - Index Signatures
Recap:
- JavaScript中的物件屬性型別為 string 或 Symbol。其他型別仍可運作程式碼,是因為JS將其強制轉為string。
- index signatures syntax
type或interface 型別名稱 = {
[屬性代替名稱: key型別]: value型別
}
index signatures 使用 readonly - 防止對 index 賦值
interface ReadonlyStringArray {
readonly [index: number]: string;
}