為 TypeScript 物件中的索引成員強制型別
    
    Shuvayan Ghosh Dastidar
    2023年1月30日
    
    TypeScript
    TypeScript Map
    
- 使用對映型別為 TypeScript 物件中的索引成員強制型別
 - 使用帶有對映型別的泛型型別來強制 TypeScript 物件中的索引成員的型別
 - 
          
            使用 
Record型別為 TypeScript 物件中的索引成員強制型別 
TypeScript 是一種強型別語言,所有用作該語言一部分的結構都是強型別的。有像介面或型別這樣的結構,它們是原始型別和使用者定義型別的組合。
甚至可以有複雜的型別,如對映或索引型別,它們在 TypeScript 中屬於對映型別的範疇。本教程將演示如何在 TypeScript 中使用對映型別。
使用對映型別為 TypeScript 物件中的索引成員強制型別
對映型別可以表示具有固定模式的物件,該模式具有固定型別的鍵和 TypeScript 中物件中的值。它們建立在索引簽名的語法之上。
type NumberMapType = {
    [key : string] : number;
}
// then can be used as
const NumberMap : NumberMapType = {
    'one' : 1,
    'two' : 2,
    'three' : 3
}
除了固定物件鍵的型別外,對映型別還可用於使用索引簽名更改物件中所有鍵的型別。
interface Post {
    title : string;
    likes : number;
    content : string;
}
type PostAvailable = {
    [K in keyof Post] : boolean;
}
const postCondition : PostAvailable = {
    title : true,
    likes : true,
    content : false
}
下面使用介面 Post 的鍵並將它們對映到不同的型別,布林值。
使用帶有對映型別的泛型型別來強制 TypeScript 物件中的索引成員的型別
對映型別也可用於建立泛型型別物件。泛型型別可用於建立具有動態型別的型別。
enum Colors {
    Red,
    Yellow,
    Black
}
type x = keyof typeof Colors;
type ColorMap<T> = {
    [K in keyof typeof Colors] : T;
}
const action : ColorMap<string> = {
    Black : 'Stop',
    Red : 'Danger',
    Yellow : 'Continue'
}
const ColorCode : ColorMap<Number> = {
    Black : 0,
    Red : 1,
    Yellow : 2
}
在上面的示例中,列舉 Colors 已用於對映型別物件,並且已根據 ColorMap<T> 支援的泛型型別強制執行不同的型別。
使用 Record 型別為 TypeScript 物件中的索引成員強制型別
Record 型別是 TypeScript 中的內建型別,可用於對 TypeScript 中的物件強制執行型別。Record 型別接受兩個欄位:鍵的型別和物件中的值。
它可以看作是在其他程式語言中找到的地圖。
const LogInfo : Record<string, string> = {
    'debug' : 'Debug message',
    'info' : 'Info message',
    'warn' : 'Warning message',
    'fatal' : 'Fatal error'
}
const message = LogInfo['debug'] + " : Hello world";
console.log(message);
輸出:
Debug message : Hello world
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
